简体   繁体   中英

django.db.utils.IntegrityError: null value in column - but value is not null

I am using Django Rest Framework and in my serialiazers.py

class MeetingSerializer(serializers.ModelSerializer):
    meeting_organiser = serializers.HiddenField(default=serializers.CurrentUserDefault())

    class Meta:
        model = Meeting
        fields = '__all__'

The Meeting model in my models.py is like:

class Meeting(models.Model):
    [some fields here...]
    meeting_organiser = models.ForeignKey(User, default=1)
    [more fields here...]

However, when I try to do a save() to the Meeting model I get this error:

django.db.utils.IntegrityError: null value in column "meeting_organiser" violates not-null constraint

I tried to debug and added in the serializers.py :

def save(self):
    print(self.validated_data)

and in models.py :

def save(self, *args, **kwargs):
    print(self.meeting_organiser.username)

In both cases, the meeting organiser object was not null and it contained the right values.

You need to add a permission such as IsAuthenticated to make sure the request is authenticated.

Otherwise, you'll get a AnonymousUser which translates to None and I assume that as this parameter is explicitly given, the model's default doesn't apply.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM