简体   繁体   English

“ user_id”列中的空值违反了非空约束Django形式

[英]null value in column “user_id” violates not-null constraint Django form

Trying to implement a file upload for a user profile page. 尝试为用户个人资料页面实施文件上传。 I am recieving the following error: 我收到以下错误:

null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (35, profile/{now:%Y/%m/YmdHMSext_xg2iZ6M, null, null). “ user_id”列中的null值违反了非null约束细节:失败行包含(35,配置文件/ {now:%Y /%m / YmdHMSext_xg2iZ6M,null,null)。

I've read that it probably has something to do with the User_ID, I tried passing form.user = request.user, but that didn't work. 我已经读到它可能与User_ID有关,我尝试传递form.user = request.user,但这没有用。 There are also two nulls, not just one. 还有两个空值,而不仅仅是一个。

Models.py 型号

class User(AbstractUser):
    # First Name and Last Name do not cover name patterns
    # around the globe.
    name = models.CharField(_('Name of User'), blank=True, 
    max_length=255)
    #accepted_terms_of_service = models.Booleanfield()

    def __str__(self):
        return self.username

    def get_absolute_url(self):
        return reverse('users:detail', kwargs={'username': 
self.username})

# Profile Image
def upload_to(instance, filename):
    now = timezone_now()
    base, ext = os.path.splitext(filename)
    ext = ext.lower()
    return "profile/{now:%Y/%m/%Y%m%d%H%M%S}{ext}"

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, 
on_delete='CASCADE', related_name='user_profile')
    school = models.CharField(max_length=30, null=True, blank=True)
    image = models.ImageField(_("Picture"), upload_to=upload_to, 
null=True, blank=True)

    def __str__(self):
        return self.user.username

views.py views.py

@login_required
def add_image(request):
     form = ProfileImageForm()
     #form.user = request.user
     if request.method == "POST":
         form = ProfileImageForm(data=request.POST, files=request.FILES)
     if form.is_valid():
         form.save()
         return redirect('userPage')
     else:
         return render(request, "users/user_image_form.html", {"form": form
        })

forms.py 表格

class ProfileImageForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ["image"]

This is because in your Profile model you add user column as ForeignKey which enforce to NOT NULL so the error throw. 这是因为在您的Profile模型中,您将user列添加为ForeignKey,并将其强制设置为NOT NULL从而引发错误。 To solve this you need to modify add_image method something like this 为了解决这个问题,您需要修改add_image方法,像这样

@login_required
def add_image(request):
     form = ProfileImageForm()
     #form.user = request.user
     if request.method == "POST":
         form = ProfileImageForm(data=request.POST, files=request.FILES)
     if form.is_valid():
         form = form.save(commit=False) # change is here
         form.user=request.user.pk # change is here
         form.save()
         return redirect('userPage')
     else:
         return render(request, "users/user_image_form.html", {"form": form

The request.user.pk value get if you are logged in. But if you are logged in you need to assisn form.user = your_specified_id which id exists in User table. 如果登录,则获得request.user.pk值。但是,如果登录,则需要设置form.user = your_specified_id ,该ID在User表中存在。 If your case is, you are admin and you need to add an image to other users, so that you need to pass the user id in your add_image method. 如果是这种情况,您是admin,则需要向其他用户添加图像,以便您需要在add_image方法中传递用户ID。

Add in ProfileImageForm.py add user in field list ProfileImageForm.py添加在字段列表中添加user

I think its not necessary to have both Profile Model and Custom User Model . 我认为没有必要同时拥有Profile Model和Custom User Model Because, as you are customizing the User model already, why not put Profile model's fields to User model as well. 因为,当您已经在自定义用户模型时,为什么不将Profile模型的字段也放到User模型中。 You can approach like this: 您可以这样处理:

# model

def upload_to(instance, filename):
    now = timezone_now()
    base, ext = os.path.splitext(filename)
    ext = ext.lower()
    return "profile/{now:%Y/%m/%Y%m%d%H%M%S}{ext}"


class User(AbstractUser):
    name = models.CharField(_('Name of User'), blank=True, 
    max_length=255)
    school = models.CharField(max_length=30, null=True, blank=True)
    image = models.ImageField(_("Picture"), upload_to=upload_to, 
                              null=True, blank=True)

    def __str__(self):
        return self.username

    def get_absolute_url(self):
        return reverse('users:detail', kwargs={'username': 
self.username})

# views

@login_required
def add_image(request):
     form = ProfileImageForm(data=request.POST or None, file=request.FILES or None, instance=request.user)
     if request.method == "POST":

        if form.is_valid():
             form.save()
             return redirect('userPage')

     return render(request, "users/user_image_form.html", {"form": form
        })

# forms.py

class ProfileImageForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ["image"]

Update 更新资料

You can create a post_save signal, which will create a Profile Instance after each User is created. 您可以创建一个post_save信号,该信号将在创建每个用户后创建一个配置文件实例。

def create_user_profile(sender, instance, created, **kwargs):

    if created:
        profile = Profile(user=instance)
        profile.save()

post_save.connect(create_user_profile,
                  sender=User,
                  dispatch_uid="profilecreation-signal")

Now in your form, you can directly pass this Profile instance: 现在在您的表单中,您可以直接传递此Profile实例:

@login_required
def add_image(request):
     form = ProfileImageForm(data=request.POST, files=request.FILES, instance=request.user.profile)

     if request.method == "POST":
         if form.is_valid():
             form.save()
             return redirect('userPage')
     else:
         return render(request, "users/user_image_form.html", {"form": form
        })

For existing user, you can create Profile from shell: 对于现有用户,可以从shell创建Profile:

for user in User.objects.all():
    Profile.objects.get_or_create(user=user)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 “ user_id”列中的空值违反了非空约束 - null value in column “user_id” violates not-null constraint “ user_id”列中的null值违反了非null约束Django - null value in column “user_id” violates not-null constraint Django Django:“user_id”列中的 null 值违反非空约束 - Django: null value in column “user_id” violates not-null constraint “user_id”列中的 Django REST POST null 值违反非空约束 - Django REST POST null value in column “user_id” violates not-null constraint 提交表单时,为什么Django在“ user_id”列中引发IntegrityError:null值违反了非null约束? - Why does Django raised IntegrityError :null value in column “user_id” violates not-null constraint when a form is committed? IntegrityError:错误:“ user_id”列中的空值违反了非空约束 - IntegrityError: ERROR: null value in column “user_id” violates not-null constraint “user_id”列中的空值违反了非空约束详细信息: - null value in column "user_id" violates not-null constraint DETAIL: null “user_id”列中的值违反了非空约束 DRF - null value in column "user_id" violates not-null constraint DRF 我如何解决“user_id”列中的错误 null 值违反非空约束? - How i can solve error null value in column “user_id” violates not-null constraint? Django:关系的“id”列中的 null 值违反非空约束 - Django : null value in column "id" of relation violates not-null constraint
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM