Django 1.8:在视图中将用户添加到Modelform:not null constraint失败

时间:2015-12-23 19:54:17

标签: django django-forms django-views

我知道这里有很多类似的问题,但是他们似乎都没有使用ModelForm在Django 1.8中查看我的观点。

我有一个用户配置文件表单,只要我在模板上下文中有每个必填字段,但我只希望每个登录用户填写自己的表单。

我在这里做错了,我不确定问题是什么。有人可以纠正我吗?我花了几个小时看其他帖子并尝试SO的各种建议。我得到“NOT NULL约束失败:camp_userprofile.user_id”

这是我的models.py:

class UserProfile(models.Model):

    user = models.OneToOneField(User) 
    picture = models.ImageField(upload_to='profile_images', blank=True)
    city = models.CharField(max_length = 20)  
    needs_camp_bike = models.BooleanField(default=False) 
    diet_lifestyle = models.CharField(max_length = 200, choices=What_are_you, null=True, blank=True)
    meal_restrictions = models.CharField(max_length = 200, blank= True)
    other_restrictions = models.CharField(max_length=100, blank=True)
    arrival_day =  models.IntegerField(choices=Days)
    departure_day = models.IntegerField(choices=Days)
    date = models.DateTimeField(auto_now_add=True, blank=True)

    def __str__(self):
        return '%s %s %s %s %s %s %s %s %s' %(
            self.user,  self.picture, self.city, 
            self.needs_camp_bike, 
            self.diet_lifestyle, self.meal_restrictions, self.other_restrictions, 
            self.arrival_day, self.departure_day
            )

我的forms.py class UserProfileForm(ModelForm):

class Meta:
    Fish = "Fish"
    Mammal = "Mammal"
    Vegetarian = "Vegetarian"
    Omnivore = "Omnivore"
    Onions = "Onions"
    Cucumber = "Cucumber"
    Peppers = "Peppers"
    Gluten_free = "Gluten_free"
    Vegan = "Vegan"
    Shellfish = "Shellfish"
    Olives = "Olives"
    Pork = "Pork"
    Soy = "Soy"
    Dairy = "Dairy"
    Cilantro = "Cilantro"
    Quinoa = "Quinoa"
    Nightshades = "Nightshades"
    Nuts = "Nuts"
    Pescaterian = "Pescaterian"

    Restrictions = (
      (Mammal, "Mammal"),
      (Onions, "Onions"),
      (Cilantro, "Cilantro"),
      (Soy, "Soy"),
      (Dairy, "Dairy"),
      (Quinoa, "Quinoa"),
      (Pork, "Pork"),
      (Olives, "Olives"),
      (Dairy, "Dairy"),
      (Peppers, "Peppers"),
      (Cucumber, "Cucumber"),
      (Nightshades, "Nightshades"),
      (Nuts, "Nuts")
    )

    model = UserProfile
    fields = ('picture', 'city', 
            'needs_camp_bike', 'diet_lifestyle',
            'other_restrictions', 'arrival_day', 
            'departure_day', 'meal_restrictions')

    widgets = {
        'meal_restrictions': forms.widgets.CheckboxSelectMultiple(choices=Restrictions),
    }

和我的views.py

@login_required
def profile(request):
    form = UserProfileForm(request.POST)
    print(request.user)
    if request.method == 'POST':
        if form.is_valid():
            form.save(commit=False)
            form.user =request.user.username
            form.save(commit=True)
        else:
            print(messages.error(request, "Error"))
    return render(request, "profile.html", RequestContext(request, {'form': form, 'profile': profile,}))

1 个答案:

答案 0 :(得分:1)

您不应该form.user = request.user.username,因为form.user无法将用户添加到表单中。您应捕获form.save(commit=false)返回的对象,然后将用户分配给该对象并保存。

此外,您无法使用username分配用户字段,username只是字符串而不是User对象。你应该这样做:

if form.is_valid():
    userprofile = form.save(commit=False)
    userprofile.user = request.user
    userprofile.save()