I am attempting to build a dummy news site to learn django.
I am running into the stated error when performing a POST request to create a new article which is linked to a signed in user via the author ForeignKey.
Users are handled using JWT on the front end.
I have been stuck on this for a few days and am out of places to look for answers.
Here are the serializers:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'password', 'email']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = User.objects.create_user(**validated_data)
return user
class ArticleSerializer(serializers.ModelSerializer):
author= UserSerializer(read_only=True)
class Meta:
model = Article
fields = '__all__'
#read_only_fields = ['author']
Here is the relevant view:
class ArticleCreateView(generics.ListCreateAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
permission_classes = (IsAuthenticated,)
def perform_create(self, serializer):
serializer.save(author=self.request.user)
and here is the relevant model:
class Article(models.Model):
headline = models.CharField(max_length=200)
subtitle = models.CharField(max_length=300)
section = models.CharField(max_length=200, blank=True, null=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='articles')
body = models.TextField()
#pub_date = models.DateTimeField(auto_now_add=True, blank=True, null=True)
endorsements = models.IntegerField(default=0, blank=True, null=True)
def __str__(self):
return self.headline
I am aware that I could set the author field to accept null/blank values and silence the error, but this would not really solve the problem as the articles would still not be linked to users.
I have also seen a few suggestions to delete all migrations and rebuild the database. I have tried this and it did not work.
Any help greatly appreciated!
Will Garvin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.