Django pet_person.user_id可能不是NULL

时间:2013-03-08 12:51:47

标签: django

我在一个应用程序上工作,宠物用户可以创建个人资料并上传他们宠物的照片。

当我访问我无法理解的个人资料页面时出现此错误。我最近创建了一个与此类似的应用程序但是我曾经看过我将我的模型与User相关联。我失误了。我感谢所有人的帮助,谢谢大家。

我试图让用户在个人资料页面上传自己的照片。

 pet_person.user_id may not be NULL

 Traceback Switch to copy-and-paste view
 C:\o\mysite\pet\views.py in Profile 
        form.save()

我认为此错误与我的模型和views.py

中的个人资料功能有关

我的models.py

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

class Person(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(max_length=100)
    image = models.FileField(upload_to="images/",blank=True,null=True)


    def __unicode__(self):
        return self.name

class Pet(models.Model):
    Person = models.ForeignKey(Person)
    description = models.CharField(max_length=100)
    image = models.FileField(upload_to="images/",blank=True,null=True)

    def __unicode__(self):
        return self.description

我的views.py部分

def Profile(request):
    form = PictureForm(request.POST ,request.FILES or None)
    if form.is_valid():
        form.save()
    return render_to_response('profile.html',{'form':PictureForm()},context_instance = RequestContext(request)
)    

我的forms.py

 from django import forms
 from django.contrib.auth.models import User
 from django.forms import ModelForm
 from pet.models import *

 class UserRegistration(ModelForm):
    username = forms.CharField(widget = forms.Textarea)
    name = forms.CharField(widget = forms.Textarea)
    email = forms.EmailField(widget = forms.Textarea)
    password = forms.CharField(widget = forms.PasswordInput(render_value=False))
    password1 = forms.CharField(label =(u'Verify Password'), widget = forms.PasswordInput(render_value=False))

    class Meta:
        model = Person
        exclude = ('user',)
        fields = ('username','email','name','password','password1')

    def clean_username(self):
        username = self.cleaned_data['username']
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError("That user is already taken , please select another ")

    def clean(self):
        if self.cleaned_data['password'] != self.cleaned_data['password1']:
            raise forms.ValidationError("The password does not match ")
        return self.cleaned_data

 class LoginForm(forms.Form):
    username = forms.CharField(widget = forms.Textarea)
    password = forms.CharField(widget = forms.PasswordInput(render_value=False))
    model = Person
    fields = ('username','password')


 class PictureForm(forms.ModelForm):

    class Meta:
        model = Person
        fields = ('image',)

@Master!

def Profile(request):
    form = PictureForm(request.POST ,request.FILES or None)
    if form.is_valid():
        event = form.save(commit=False)
        event.user=request.user
    event.save()
    return render_to_response('profile.html',{'form':PictureForm()},context_instance = RequestContext(request))    

3 个答案:

答案 0 :(得分:1)

在下面的模型中

class Person(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(max_length=100)
    image = models.FileField(upload_to="images/",blank=True,null=True)

你有一个名为user的字段,表格中的任何地方都没有提到。

根据您的模型Person字段不能为空。

克服这个问题

保存您的表单,如

`obj =  form.save(`commit = False`)`
 obj.user =Person(user=request.user) # If user is logged in 
 obj.save()

答案 1 :(得分:1)

class PictureForm(forms.ModelForm):
    class Meta:
        model = Person
        fields = ('image',)

def Profile(request):
    person = Person(user=request.user)
    if request.method == 'POST':
        form = PictureForm(request.POST ,request.FILES or None, instance=person)
        if form.is_valid():
            form.save() 
    return render_to_response('profile.html',{'form':PictureForm()},context_instance = RequestContext(request)

答案 2 :(得分:0)

我认为你的问题在于PictureForm你只需要图片字段。但是,此表单实际上适用于Person模型。您的Person需要用户和名称以及图像(事实上,图像是唯一的可选部分)。看到这些不是来自您的表单,您需要自己提供这些。见https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-a-subset-of-fields-on-the-form