Objective: Creating a new entry in database from Postman using the "POST".
I am trying to send the data from Postman and I am using nested serializing. I have changed the create method i have shared the snippet below. Also, I tried this solution but it did not work. Can someone please point out the mistake I am making?
When I am trying to post as form-data the error is {"magazine":["This field is required."]}
.
When I am trying to post it as raw data the error is Direct assignment to the forward side of a many-to-many set is prohibited. Use magazine.set() instead.
Here is my models:
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
author = models.ForeignKey('authors.Author', on_delete=models.CASCADE)
magazine = models.ManyToManyField('articles.Magazine')
def __str__(self):
return self.title
class Magazine(models.Model):
name = models.CharField(max_length=30)
title = models.CharField(max_length=100)
def __str__(self):
return self.name
This is my serializers:
class MagazineSerializer(serializers.ModelSerializer):
class Meta:
model = Magazine
fields = '__all__'
class ArticleSerializer(serializers.ModelSerializer):
author = AuthorSerializer(read_only=True, many=False)
magazine = MagazineSerializer(many=True)
class Meta:
model = Article
fields = [
'title',
'content',
'author',
'magazine',
]
def create(self, validated_data):
allmags = []
magazine = validated_data.pop('magazine')
for i in magazine:
if Magazine.objects.get(id=magazine["id"]).exists():
mags = Magazine.objects.get(id=magazine["id"])
allmags.append(mags)
else:
return Response({"Error": "No such magazine exists"}, status=status.HTTP_400_BAD_REQUEST)
validated_data['author'] = self.context['request'].user
validated_data['magazine'] = allmags
return Article.objects.create(**validated_data)
Here is my view:
class ArticleViewSet(viewsets.ModelViewSet):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
class MagazineViewSet(viewsets.ModelViewSet):
queryset = Magazine.objects.all()
serializer_class = MagazineSerializer
serializer_action_class = {
'get_articles': MagazineSerializer,
}
@action(detail=True, url_path='articles', url_name='articles')
def get_articles(self, request, pk=None):
articles = Article.objects.filter(magazine=self.kwargs.get('pk'))
serializer = ArticleSerializer(articles, many=True)
return Response(serializer.data, status=200)
This is how I tried sending data as raw:
{
"title": "New Post form Postman",
"content": "Postman content new",
"magazine": [
{
"id": 1,
"name": "The Times",
"title": "All News"
}
]
}