简体   繁体   English

NOT NULL约束失败

[英]NOT NULL constraint failed

Could someone smart explain me please where I have a bug? 有人可以向我解释我的错误吗?

I get this error when I would like to send a profile user form 我想发送个人资料用户表格时收到此错误

NOT NULL constraint failed: userprofile_userprofile.godzina_id

看起来像这样:

I have an app "userprofile" 我有一个应用“用户个人资料”

forms.py from django import forms from models import UserProfile django的forms.py从模型导入表单

class UserProfileForm(forms.ModelForm):

    class Meta:
        model = UserProfile
        fields = ('imie', 'godzina')

views.py views.py

from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from forms import UserProfileForm
from django.contrib.auth.decorators import login_required
from django.conf import settings

@login_required
def user_profile(request):
    if request.method == 'POST':
        form = UserProfileForm(request.POST, instance=request.user.profile)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/accounts/loggedin')
    else:
        user = request.user
        profile = user.profile
        form = UserProfileForm(instance=profile)
        args = {}
        args.update(csrf(request))
        args['form'] = form
        return render(request, 'user_profile.html', args)

models.py: models.py:

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

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    imie = models.CharField(max_length=150)
    godzina = models.ForeignKey('godzina.Godzina')   


User.profile = property(lambda u:UserProfile.objects.get_or_create(user=u)[0])

您可以将null=True添加到您的godzina属性:

godzina = models.ForeignKey('godzina.Godzina', null=True)

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

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