I have two required fields on my model that I would like to populate in the pre_save method of my ModelViewSet. Despite setting them there, when submitting a .create() request I still get an error that the two fields are required and thus my object cannot be created.
I did some research on this and it seems that it's related to the is_valid() check being performed before pre_save is called... the recommended solution per some stack overflow articles that I've found:
Django REST Framework, pre_save() and serializer.is_valid(), how do they work?
Django REST Framework serializer field required=false
Seems to be to override the get_validation_exclusions method. However that still doesn't seem to be working for me... I'm thinking at this point it might have to do with my model inheritance? Any help that you could provide would be greatly appreciated! This is what I'm working 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()