2015-01-20 20 views
1

我已經完成了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) 

我不知道我是怎麼應該解決這個,我已經包含了「初始= 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

你的問題是,你有一個領域pub_date設置爲隱藏式的形式,但在元,你排除。現在,當你排除它時,隱藏類型不會被設置在表單中,並且當對象被設置爲創建時,它會失敗,因爲它找不到必需的屬性。

要解決此問題,更改:

fields = ('question_text',) 

fields = "__all__" 

下面是相關文檔:https://docs.djangoproject.com/en/1.7/topics/forms/modelforms/#selecting-the-fields-to-use


現在,一個替代的解決將是(雖然不是請參閱文檔中的說明),而不是表單,您可以在模型文件中設置默認值VEL。對於這一點,你會做:

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

所以,如果什麼也沒有針對該字段中指定的插件進行到數據庫中,Django的檢查,每次分配指定的默認值。

你可以閱讀更多的default values here

+0

而不是設置由於它不包含可識別時區的日期時間,因此它是datetime.now的默認值。請參閱下面的答案。 – Shay 2015-01-20 19:04:21

+0

呵呵。我不反對你,但這是官方教程。對於剛開始的人來說,你的答案太過於IMO了。因此,我不會推薦走這條路線 – karthikr 2015-01-20 19:09:17

+0

我認爲你提出的方式是不好的做法,OP最好複製正確的做法,直到他理解了這些概念。否則他稍後會遇到問題。 – Shay 2015-01-20 19:12:36

0

最好是從QuestionForm刪除

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

和修改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()

,並設置模型字段我建議不要使用域= 「__ all__」 default=timezone.now

相關問題