Django完整性错误 - NOT NULL约束失败:zdorovo_page.category_id

时间:2017-07-20 13:32:33

标签: django django-forms

在使用Django时,我创建了一个显示不同类别的应用程序。点击它们中的任何一个,它会打开一个窗口,显示与其相关的所有页面。在同一窗口中,您可以选择在该特定类别中添加新页面。

我得到这个完整性错误类型的值为非空约束失败错误。我无法理解这个错误。请帮我理解我哪里出错了。我已经发布了所有必需的脚本。

models.py
from django.db import models
from django.template.defaultfilters import slugify

class Category(models.Model):
     name = models.CharField(max_length=128, unique=True)
     slug = models.SlugField(blank = True, null= True)

     def save(self, *args, **kwargs):
         self.slug = slugify(self.name)
         super(Category, self).save(*args, **kwargs)

     class Meta:
         verbose_name_plural = 'categories'

     def __unicode__(self):
         return self.name

class Page(models.Model):
     category = models.ForeignKey(Category)
     title = models.CharField(max_length=128)
     url = models.URLField()
     views = models.IntegerField(default=0)

     def __unicode__(self):
         return self.title

我基本上是在尝试将页面添加到现有类别中。这是我的add_page视图

views.py for add_page
def add_page(request , category_name_slug):
    category = Category.objects.get(slug = category_name_slug)
    form = PageForm()
    if request.method == 'POST':
        form = PageForm(request.POST)
        if form.is_valid():
            if category:
                page = form.save(commit = True)
                page.category = category
                page.views = 0
                page.save()
                return about(request , category_name_slug)
        else:
            print form.errors
    return render(request , 'zdorovo/add_page.html' , {'form': form , 'category': category})

关于这是一个视图,它将现有页面处理到特定类别并显示它们。

这是我的forms.py

class CategoryForm(forms.ModelForm):
    name = forms.CharField(max_length=128, help_text="Please enter the category name.")
    views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
    likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
    slug = forms.CharField(widget=forms.HiddenInput(), required=False)


    class Meta:
        model = Category
        fields = ['name',]

class PageForm(forms.ModelForm):
    title = forms.CharField(max_length=128, help_text="Please enter the title of the page.")
    url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.")
    views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)

    class Meta:
        model = Page
        exclude = ('category',)

如果有人要求我提供任何帮助,请更新我。

P.S.-所有缩进都已经过处理,没有错误。

2 个答案:

答案 0 :(得分:0)

你是如此亲密。变化:

page = form.save(commit=True)

page = form.save(commit=False)

这样,当表单转换为模型对象时,Form的对象将不会保存到数据库中。手动设置category后,它将被保存。

希望这有帮助。

答案 1 :(得分:0)

在您的页面模型类别中是必填字段。但是当你执行page = form.save(commit = True)时,它会尝试保存页面对象而不分配任何类别。因此,您将获得完整性错误。

尝试

def add_page(request , category_name_slug):
    category = Category.objects.get(slug = category_name_slug)
    form = PageForm()
    if request.method == 'POST':
        form = PageForm(request.POST)
        if form.is_valid():
            if category: 
                page = form.save(commit = False) # tells Django that "Don't send this to database yet.
                # I have more things I want to do with it.
                page.category = category
                page.views = 0
                page.save()
                return about(request , category_name_slug)
        else:
            print form.errors
    return render(request , 'zdorovo/add_page.html' , {'form': form , 'category': category})