Django POST违反了非空约束user_id

时间:2018-04-02 18:55:30

标签: django django-forms django-rest-framework

即使在这里也难以找到我的问题的答案。我知道有类似的帖子,但我仍然没有得到它。

我在尝试POST到我的" user_profile"时收到错误以下是错误和我的代码。

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

models.py,它有一个来自django.contrib.auth.models的foriegnkey导入用户

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.OneToOneField(User, on_delete=True)
    start_date = models.DateTimeField
    last_active_date = models.DateTimeField
    alias_name = models.CharField(max_length=30)
    city = models.CharField(max_length=30)
    state = models.CharField(max_length=30)
    zipcode = models.CharField(max_length=5, null=True)

serializers.py

from rest_framework import serializers
from api.models import UserProfile

class UserProfileSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    orientation = serializers.CharField(required=False, allow_blank=True, max_length=100)

    def create(self, validated_data):

        return UserProfile.objects.create(**validated_data)

userprofile.py get工作正常但是通过"的帖子违反了非空约束"

@csrf_exempt
def user_profile_list(request):
    if request.method == 'GET':
        orientation = UserProfile.objects.all().values()
        list2 = list(orientation)
        return JsonResponse(list2, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = UserProfileSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

1 个答案:

答案 0 :(得分:2)

您有read_only = True,因此在UserProfileSerializer的POST中无法使用id。 型号序列化器将帮助您。 docs