在Django中发布表单时无法保存数据

时间:2017-05-11 11:54:47

标签: python django database http request

我正在按照Django教程构建一个可以在网站中添加页面和类别的小网站,我定义了一个Page模型如下:

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

    def __str__(self):
        return self.title

并定义了如下的模型:

class PageForm(forms.ModelForm):
    title = forms.CharField(max_length=128, help_text="Please enter the title of this page")
    url = forms.URLField(max_length=200, help_text="Please enter the URL of the page")
    views = forms.IntegerField(widget=forms.HiddenInput(),initial=0)
    category = forms.ModelChoiceField(queryset=Category.objects.all(),help_text="Please choose a category for the page")

    class Meta:
        model = Page
        fields = '__all__'

和add_page的观点是:

def add_page(request):

     if request.method == 'POST':
        form = PageForm(request.POST)

        if form.is_valid():
           page = form.save(commit=True)
           print(page)
           page.views = 0
           page.save()
           return index(request)
        else:
           print('error')
           form.errors
    else:
        form = PageForm()
        context_dict = {'form':form}

    return render(request,'rango/add_page.html',context_dict)

但是当我运行网站并在字段中填写这样的信息时:

  1. 在选择窗口中选择类别“HTML”
  2. 在名称字段中填写'w3c'
  3. 在网址字段中填写“http://www.w3cshools.com
  4. 并选择“创建页面”但单击按钮后没有响应也没有将表单中的数据添加到数据库中,我尝试使用print进行调试,发现数据无法通过验证没有if块'form.is_valid()'的进程,但我无法理解为什么以及如何修改。

    我的类别模型定义为:

    class Category(models.Model):
        name = models.CharField(max_length=128, unique=True)
        views = models.IntegerField(default=0)
        likes = models.IntegerField(default=0)
        slug = models.SlugField(unique=True)
    
        def save(self,*args,**kwargs):
            self.slug = slugify(self.name)
            super(Category, self).save(*args,**kwargs)
    
        def __str__(self):
            return self.name
    

    类别表格:

    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',)
    

3 个答案:

答案 0 :(得分:0)

而不是像你在这里设置初始

views = forms.IntegerField(widget=forms.HiddenInput(),initial=0)

请使用此

views = forms.IntegerField(widget=forms.HiddenInput())

然后更改此

form = PageForm(request.POST)

到这个

form = PageForm(request.POST, initial={"views": "0"})

我指的是this post

答案 1 :(得分:0)

只需在PageForm中排除字段'category',重启服务器即可。

答案 2 :(得分:0)

改变你的观点,

def add_page(request): 
    if request.method == 'POST': 
        form = PageForm(request.POST)
        if form.is_valid(): 
            page = form.save(commit=False)
            page.views = 0 
            page.save()
            return redirect('index') 
        else: 
            render(request, 'rango/add_page.html', {'form':'form.errors'}
    else: 
        form = PageForm()
    context_dict = {'form':form}
    return render(request,'rango/add_page.html',context_dict)

保存表单时,您应该commit=False添加其他数据。