'Got a `TypeError` when calling `WordsTable.objects.create()`
I am trying to save some data in the database using serializer. I have created a model and a serializer but I get this error when I try to save the data. I have seen many answers but haven't come up with the solution.
I get this error:Got a TypeError when calling WordsTable.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to WordsTable.objects.create(). You may need to make the field read-only, or override the WordsTableSerializer.create() method to handle this correctly.
models.py:
class WordsTable(models.Model):
session_id = models.IntegerField(
db_column="session_ID", blank=True, null=True
) # Field name made lowercase.
user_id = models.IntegerField(
db_column="user_ID", blank=True, null=True
) # Field name made lowercase.
date = models.DateField(blank=True, null=True, default=datetime.date.today)
hour = models.TimeField(blank=True, null=True, default=datetime.date.today)
run_label = models.IntegerField(blank=True, null=True)
status = models.IntegerField(blank=True, null=True)
word1 = models.CharField(max_length=45, blank=True, null=True)
word2 = models.CharField(max_length=45, blank=True, null=True)
word3 = models.CharField(max_length=45, blank=True, null=True)
word4 = models.CharField(max_length=45, blank=True, null=True)
word5 = models.CharField(max_length=45, blank=True, null=True)
class Meta:
db_table = "words_table"
The serializer:
class WordsTableSerializer(serializers.ModelSerializer):
class Meta:
model = WordsTable
fields = "__all__"
Views.py:
#API
@api_view(["POST"])
def save_words(request):
if request.method == "POST":
saveserialize = WordsTableSerializer(data=request.data)
if saveserialize.is_valid():
saveserialize.save()
return Response(saveserialize.data, status=status.HTTP_201_CREATED)
return Response(saveserialize.data, status=status.HTTP_400_BAD_REQUEST)
The data I'm trying to post:
{
"session_id" : 4567,
"word1" : "Pants",
"word2" : "Shock",
"word3" : "Cucumber"
}
What do I have to add? it's the first time I use serializers so I'm a bit confused. Thank you!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
