I have two required fields in my model that I would like to fill in the pre_save method of my ModelViewSet. Despite setting them up, when sending a .create () request, I still get an error that two fields are required and therefore my object cannot be created.
I did some research on this, and it looks like this is due to the is_valid () check being done before the pre_save is called ... the recommended solution for some articles I found:
Django REST Framework, pre_save () and serializer.is_valid (), how do they work?
Django REST Framework serialization field required = false
It seems to need to override the get_validation_exclusions method. However, this still does not work for me ... I think at this point this may be relevant to my model inheritance? Any help you could provide would be greatly appreciated! This is what I work with -
serializers.py
class DaytimeSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Daytime
def get_validation_exclusions(self):
exclusions = super(DaytimeSerializer, self).get_validation_exclusions()
return exclusions + [ 'creation_datetime', 'creator_userprofile' ]
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
phone_number = models.CharField(max_length=12)
friends = models.ManyToManyField('self', related_name = 'friends')
field4 = models.CharField(max_length=300, blank=True)
def __unicode__(self):
return self.user.username + ' UserProfile'
class Activity(models.Model):
field1 = models.CharField(max_length=300)
field2 = models.CharField(max_length=300, blank=True)
creation_datetime = models.DateTimeField()
creator_userprofile = models.ForeignKey(UserProfile)
field3 = models.ManyToManyField('self')
field4 = models.BooleanField()
field5 = models.CharField(max_length=300, blank=True)
def __unicode__(self):
return self.field1 + ' | ' + self.creator_userprofile.user.username
class Meta:
abstract = True
class Daytime(Activity):
field6 = models.ManyToManyField(UserProfile, related_name='abc')
field7 = models.BooleanField()
myviewsfile.py
class DaytimeViewSet(viewsets.ModelViewSet):
queryset = Daytime.objects.all()
serializer_class = DaytimeSerializer
def pre_save(self, obj):
obj.creator_userprofile = UserProfile.objects.get(user__username = self.request.user)
obj.creation_datetime = timezone.now()