我已經完成了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非常陌生!
乾杯, 保羅
而不是設置由於它不包含可識別時區的日期時間,因此它是datetime.now的默認值。請參閱下面的答案。 – Shay 2015-01-20 19:04:21
呵呵。我不反對你,但這是官方教程。對於剛開始的人來說,你的答案太過於IMO了。因此,我不會推薦走這條路線 – karthikr 2015-01-20 19:09:17
我認爲你提出的方式是不好的做法,OP最好複製正確的做法,直到他理解了這些概念。否則他稍後會遇到問題。 – Shay 2015-01-20 19:12:36