我在views.py中使用以下代码
def when(request):
log.debug("test....")
reportform = ReportForm()
if request.method == 'POST':
if reportform.is_valid():
log.debug("test:%s",reportform)
reportform = reportform.save()
return render_to_response('incident/when.html',{'newreport_menu': True,
'form': reportform },context_instance=RequestContext(request))
我的模板是
{{ form.manual_date_time }}
<p id=ir-nextbutn><a href="{% url incident.views.media %}">
<form action="/member/media/" method="POST"> {% csrf_token %}
{% include "buttons/next.html" %}
</form>
models.py
class Report(models.Model):
user = models.ForeignKey(User, null=False)
incident_number = models.CharField('Incident Number', max_length=100)
device_id = models.CharField('Device Id', max_length=100)
app_uuid = models.CharField('Unique App Id', max_length=100)
created_date_time = models.DateTimeField('Created')
manual_date_time = models.DateTimeField('Another time', null=True, blank=True)
sent_date_time = models.DateTimeField('Sent')
incident_description = models.TextField('Incident description', null=True, blank=True)
这里我将日期时间字段保存在数据库中。如果用户单击下一个按钮保存并转到下一页,则在字段中输入时间和日期。但是它不存储数据。我正在使用MySql db
答案 0 :(得分:0)
在我看来,您没有在表单中填充用户字段。 Report模型将user作为非null外键,因此可能会给您带来麻烦。你需要明确添加 表单未填充然后保存的字段:
if reportform.is_valid():
log.debug("test:%s",reportform)
report = reportform.save(commit=False)
report.user = request.user #assuming a login_required decorator
report.incident_number = ...
....
report.save()
因此我们使用表单提供的字段从表单创建报表对象。由于报表对象仍然不完整,我们现在不提交。然后我们添加剩余的字段并保存。
答案 1 :(得分:0)
您没有将任何数据应用于表单,因此无法使用该表单。
def when(request):
if request.method == 'POST':
# Form with POST'ed data
reportform = ReportForm(
data=request.POST,
)
if reportform.is_valid():
log.debug("test:%s",reportform)
reportform = reportform.save()
# You should redirect to a different page at this point
# This will avoid double POST'ing and saving
redirect_to = request.POST.get(
'next',
reverse('name-of-url-defined-in-your-urls.py')
)
return HttpResponseRedirect(redirect_to)
else:
# Check the errors, they *should* appear when the form is rendered
pass
else:
# Blank form, no data
reportform = ReportForm()
return render_to_response(
'incident/when.html',
{
'newreport_menu': True,
'form': reportform,
},
context_instance=RequestContext(request)
)
<强>更新强>
此外,您的表单未包含在form
标记中。您的“下一步”按钮必须是input
或button
type="submit"
<form action="/member/media/" method="POST"> {% csrf_token %}
<input name="next" type="hidden" value="{{ url_to_redirect_to }}"/>
{{ form }}
<input type="submit" name="save" value="save"/>
OR
<button type="submit">Save</button>
</form>
旁注:
您可以将auto_now_add=True
添加到created_date_time
,以避免必须自行设置并停止编辑并显示在ModelForm
created_date_time = models.DateTimeField('Created', auto_now_add=True,)