Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework (DRF): Set current user id as field value

Tags:

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?

like image 497
Dunaevsky Maxim Avatar asked Jan 22 '15 10:01

Dunaevsky Maxim


People also ask

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

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.

What is write only field Django REST framework?

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.


2 Answers

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.

like image 141
mariodev Avatar answered Sep 21 '22 03:09

mariodev


In new DRF you can write

owner = serializers.HiddenField(     default=serializers.CurrentUserDefault() ) 

See http://www.django-rest-framework.org/api-guide/validators/#currentuserdefault

like image 39
TIO Avatar answered Sep 20 '22 03:09

TIO