I have a model with unique_together on the user and the created date

class ModelClass(models.Model):
    created = models.DateField(_("Date"), default=datetime.date.today, 
editable=True)
    user = models.ForeignKey(AUTH_USER_MODEL)

    class Meta:
        unique_together = ('created', 'user')

On my ModelViewSet I had a perform_create that would default the user with 
the user in the request.

class MyModelViewSet(viewsets.ModelViewSet):
    def get_queryset(self):
        user = self.request.user
        model = getattr(self.serializer_class.Meta, 'model')
        return model.objects.filter(user=user)

    def perform_create(self, serializer):
        serializer.save(user = self.request.user)


Once I added the unique_together to the model posts now fail.  The reason 
is that the create and is_valid happens before the perform_create() method.

I am looking at a way to add the request.user to the serializer object 
before the is_valid is called.  I tried overloading the serializer and 
adding the user a few different ways.

    def create(self, request, *args, **kwargs):
        # try 1
        request.data['user'] = request.user.id
        serializer = self.get_serializer(data=request.data)

        # try 2
        serializer = serializers.MySerializer()
        serializer.data = request.data
        serializer.data.user = self.request.user

        # try 3
        request.data['user'] = request.user.id
        return super(MyModelViewSet, self).post(request, *args, **kwargs)


Everytime I post, I get the following error:
{
    "user": [
        "This field is required."
    ]
}


Thanks.

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to