M
M
marselabdullin2020-07-07 23:05:30
Django
marselabdullin, 2020-07-07 23:05:30

How to pass user through rest of django?

There is an event model that is tied to the user. When creating an event through rest, I set all the parameters, except for the user, but he swears that the user is null. When creating through the admin panel and the site itself, the user is taken through request.user, but I don’t know how to do this through the rest

models.py:

class Event(models.Model):
    """Event which create user"""
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                            on_delete=models.CASCADE, verbose_name="Пользователь")
    title = models.CharField(max_length=70, verbose_name="Название")
    content = models.CharField(max_length=300, verbose_name="Содержание")
    event_date = models.DateTimeField(verbose_name="Дата события")

    def __str__(self):
        return self.title


serializers.py:
class EventSerializer(serializers.Serializer):
    title = serializers.CharField()
    content = serializers.CharField()
    event_date = serializers.DateTimeField()


    def create(self, validated_data):
        return Event.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.title = validated_data.get('title', instance.title)
        instance.content = validated_data.get(
            'content', instance.content)
        instance.event_date = validated_data.get('event_date',
             instance.event_date)
        instance.save()
        return instance


views.py (serializer part):
class EventView(APIView):
    def get(self, request):
        events = Event.objects.all()
        serializer = EventSerializer(events, many=True)
        return Response({"events": serializer.data})

    def post(self, request):
        event = request.data.get('event')
        serializer = EventSerializer(data=event)
        if serializer.is_valid(raise_exception=True):
            event_saved = serializer.save()
        return Response({"success": "Event created successfully"})

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Tikhonov, 2020-07-08
@tumbler

DRF allows you to do self.request.user in the view, and in serializers - to reach the view through the context: self.context['view'].request.user

W
Web Dentist, 2020-07-08
@kgb_zor

There are several options here.
1. You add user_id to your data to get a User instance.
2. Since this data can be easily changed and if it is important for you that the event is created for a user who is authorized, then you need to use JWT (Json Web Token).

S
szelga, 2020-07-08
@szelga

try SessionAuthentication . The documentation promises that then getyour postAPIView will also have request.user.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question