【问题标题】:NOT NULL constraint failedNOT NULL 约束失败
【发布时间】:2015-04-22 02:21:34
【问题描述】:

谁能给我解释一下我哪里有错误?

我想发送个人资料用户表单时收到此错误

NOT NULL constraint failed: userprofile_userprofile.godzina_id

我有一个应用“用户资料”

forms.py 从 django 导入表格 从模型导入用户配置文件

class UserProfileForm(forms.ModelForm):

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

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:

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])

【问题讨论】:

    标签: python django python-2.7 django-views


    【解决方案1】:

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

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

    【讨论】:

    • @user3904216(只是为了确保)您是否使用syncdb/migrate 来保存表架构中的更改?
    猜你喜欢
    • 2018-08-24
    • 2022-01-19
    • 2021-11-16
    • 2020-12-18
    • 2021-03-20
    • 2020-02-11
    • 2019-02-13
    • 2017-12-31
    • 2019-05-06
    相关资源
    最近更新 更多