我是Django的新手,我正在尝试使用ModelForm保存数据。模板'Vlozit'有一个ModelForm,在提交时,我希望保存在数据库中的数据和重定向到base.html,它实际上从数据库加载数据并列出输出。问题是一切正常,但数据没有保存。请帮我找到我所缺少的东西。谢谢。
以下是模型:
class Customer(models.Model):
Name = models.CharField(max_length=30)
Description = models.CharField(max_length=150)
Creation_Date = models.DateField(default=datetime.now)
Active = models.BooleanField(default=False)
def __unicode__(self):
return self.Name
Customers = models.Manager()
这是ModelForm:
class CustomerForm(forms.ModelForm):
Description = forms.CharField(widget=forms.Textarea)
class Meta:
model = Customer
以下是观点:
def vlozit(request):
if request.method == 'POST':
form = CustomerForm(request.POST, instance=Customer)
if form.is_valid():
form.save(True)
return HttpResponseRedirect(reverse('Base.html'))
else:
form = CustomerForm()
return render_to_response("Vlozit.html", {'form': form}, context_instance = RequestContext(request))
这是'Vlozit'模板:
{% extends "base.html" %}
{% block head %}
{{ form.media }}
<script>
$(function() {
$( "#id_Creation_Date" ).datepicker();
});
</script>
{% endblock %}
{% block title %}{{block.super}} - Vlozit{% endblock %}
{% block content %}
<div id="content">
<form method="POST" action="{% url url_home %}">
{% csrf_token %}
<table>
<tr>
<td>Name</td>
<td>{{ form.Name }}</td>
</tr>
<tr>
<td>Description</td>
<td>{{ form.Description }}</td>
</tr>
<tr>
<td>Creation Date</td>
<td>{{ form.Creation_Date }}</td>
</tr>
<tr>
<td>Active</td>
<td>{{ form.Active }}</td>
</tr>
</table>
<input type="submit" value="Vlozit">
</form>
</div>
{% endblock content %}
答案 0 :(得分:3)
正如蒂米在评论中所说,你不会发现表格无效的情况。您不仅不会在模板中显示错误,而且如果form.is_valid()
为False,您甚至也不会重新显示模板。将视图的最后一行移回一个缩进级别,然后将{{ form.errors }}
添加到模板中。