从Django的官方教程创建表单

时间:2015-01-20 18:44:29

标签: python django

我已经完成了Django官方教程,我一直在尝试根据现有模型创建一个表单。因此,除了能够从管理屏幕创建民意调查/选择之外,我还希望将其复制为用户可以与之交互的表单。

但是,当我实际在html呈现的页面上提交表单时,我收到了返回的完整性错误。

IntegrityError at /polls/add_poll/
polls_question.pub_date may not be NULL
Request Method: POST
Request URL:    http://127.0.0.1:8000/polls/add_poll/
Django Version: 1.7.1
Exception Type: IntegrityError
Exception Value:    
polls_question.pub_date may not be NULL
Exception Location: C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 485
Python Executable:  C:\Python27\python.exe
Python Version: 2.7.8

追溯到:

C:\Users\Paul.Zovighian\desktop\project\mysite\polls\views.py in add_poll
            form.save(commit=True) 

我不确定我应该如何缓解这种情况,我已经将'initial = datetime.now()包含在ModelForm中但是没有修复它。

forms.py

from django import forms
from .models import Question, Choice
from datetime import datetime

class QuestionForm(forms.ModelForm):
    question_text = forms.CharField(max_length=200, help_text="Please enter the question.")
    pub_date = forms.DateTimeField(widget=forms.HiddenInput(), initial = datetime.now())

    class Meta:
        model = Question
        fields = ('question_text',)

models.py

import datetime

from django.db import models
from django.utils import timezone


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __unicode__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'

views.py

def add_poll(request):
    # A HTTP POST?
    if request.method == 'POST':
        form = QuestionForm(request.POST)

        # Have we been provided with a valid form?
        if form.is_valid():
            # Save the new category to the database.
            form.save(commit=True)

            # Now call the index() view.
            # The user will be shown the homepage.
            return render(request, 'polls/index.html', {})
        else:
            # The supplied form contained errors - just print them to the terminal.
            print form.errors
    else:
        # If the request was not a POST, display the form to enter details.
        form = QuestionForm()

    # Bad form (or form details), no form supplied...
    # Render the form with error messages (if any).
    return render(request, 'polls/add_poll.html', {'form': form})

希望这些信息足以帮助别人帮助我!很高兴提供其他任何东西。关于我的方法的任何提示也非常受欢迎,我是django的新手!

干杯, 保罗

2 个答案:

答案 0 :(得分:2)

您的问题是,您的表单中的字段pub_date设置为隐藏类型,但在元数据中,您将其排除。现在,当您将其排除时,隐藏类型不会在表单中设置,并且当对象设置为创建时,它将失败,因为它找不到必需的属性。

要解决此问题,请更改:

fields = ('question_text',)

fields = "__all__"

以下是相关文档:https://docs.djangoproject.com/en/1.7/topics/forms/modelforms/#selecting-the-fields-to-use


现在,备用修复程序(虽然尚未在文档中介绍),而不是表单,您可以在模型级别设置默认值。为此,你会这样做:

pub_date = models.DateTimeField('date published', default=datetime.datetime.now) 

因此,每次在数据库中执行插入操作时,如果没有为该字段指定任何内容,则django会检查并分配指定的默认值。

您可以在default values here

上阅读更多内容

答案 1 :(得分:0)

最好删除

pub_date = forms.DateTimeField(widget=forms.HiddenInput(), initial = datetime.now())

来自QuestionForm并修改fields

fields = ('question_text', 'pub_date', )

如果pub_date可以发布null

pub_date = models.DateTimeField(null=True)

使隐藏在表单中的pub_date覆盖__init__

def __init__(self): self.fields['pub_date'].widget = forms.widgets.HiddenInput()

并设置模型字段default=timezone.now