I have model NewsModel and 2 serializers for him:
models.py
class NewsModel(models.Model): title = models.CharField('Заголовок', max_length=255, help_text='Максимальная длина - 255 символов') announce = models.TextField('Анонс', help_text='Краткий анонс новости') author = models.ForeignKey(settings.AUTH_USER_MODEL, help_text='Автор новости', related_name='news') full_text = models.TextField('Полный текст новости', help_text='Полный текст новости') pub_date = models.DateTimeField('Дата публикации', auto_now_add=True, default=timezone.now, help_text='Дата публикации') def comments_count(self): return NewsComment.objects.filter(news=self.id).count() def get_author_full_name(self): return self.author.get_full_name() class Meta: db_table = 'news' ordering = ('-pub_date',)
serilizers.py:
from rest_framework import serializers from .models import NewsModel from extuser.serializers import UserMiniSerializer class NewsReadSerializer(serializers.ModelSerializer): author = UserMiniSerializer() class Meta: model = NewsModel fields = ('id', 'title', 'announce', 'comments_count', 'reviews', 'author_name') def get_author_full_name(self, obj): return obj.get_author_full_name() class NewsWriteSerializer(serializers.ModelSerializer): def validate_author(self, value): value = self.request.user.id return value class Meta: model = NewsModel
I select serializers in the api.py:
class NewsList(ListCreateAPIView): queryset = NewsModel.objects.order_by('-pub_date') def get_serializer_class(self, *args, **kwargs): if self.request.method == 'GET': return NewsReadSerializer return NewsWriteSerializer class Meta: model = NewsModel
But when I will create NewsModel item, I see Error 400: Bad request [{'author': 'This field is required'}]
How I can set current user id as NewsItem.author value on creating new item?
The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.
From DRF v3 onwards, setting a field as read-only or write-only can use serializer field core arguments mentioned as follows. write_only. Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.
I don't think you're using the serializer properly. A better practice to set request related data is to override perform_create
in your view:
def perform_create(self, serializer): serializer.save(author=self.request.user) def perform_update(self, serializer): serializer.save(author=self.request.user)
and then set your author serializer to read-only:
author = UserMiniSerializer(read_only=True)
this way you can simply use one single NewsSerializer
for both read and write actions.
In new DRF you can write
owner = serializers.HiddenField( default=serializers.CurrentUserDefault() )
See http://www.django-rest-framework.org/api-guide/validators/#currentuserdefault
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With