我有一个表格:
class OrderForm(forms.Form):
delivery_time = models.CharField(max_length=100)
address_city = models.CharField(max_length=40)
address_street = models.CharField(max_length=40)
address_building = models.CharField(max_length=40)
这是我的看法:
def submit(request):
args = {}
args['form'] = OrderForm()
if request.POST:
order_form = OrderForm(request.POST)
if order_form.is_valid():
user = request.user
address_city = order_form.cleaned_data.get('address_city')
address_street = order_form.cleaned_data.get('address_street')
address_building = order_form.cleaned_data.get('address_building')
delivery_time = order_form.cleaned_data.get('delivery_time')
new_order = Order(address_city=address_city,
address_street=address_street,
address_building=address_building,
delivery_date=delivery_time, client=user)
new_order.save()
Basket.objects.filter(client=user).delete()
return redirect('/order/')
else:
args['form'] = order_form
else:
return render(request, 'order_page.html', args)
我猜问题出在我的模板上:
<form class="form-horizontal" action="{% url 'order_submit' %}" method="post">
{% csrf_token %}
<div class="control-group">
<label class="control-label" for="address">City<sup>*</sup></label>
<div class="controls">
<input type="text" id="address" placeholder="City name" name="address_city">
</div>
</div>
...
我想问题是我不仅仅使用
{{form}}
。但是我确实需要这些样式来构成我的表单。我对我的注册模板也做同样的事情,并且可以正常工作。注册表单继承了UserCreationForm
并受User
模型限制,但是我的OrderForm继承了form.Form
。会是什么Order model:
class Order(models.Model):
state_choices = ('ACTIVE', 'COMPLETED', 'FROZEN')
order_date = models.DateTimeField(auto_now_add=True)
delivery_time = models.CharField(max_length=100)
address_city = models.CharField(max_length=40)
address_street = models.CharField(max_length=40)
address_building = models.CharField(max_length=40)
state = models.CharField(max_length=200, default='ACTIVE')
client = models.ForeignKey(CustomUser)
最佳答案
这里的基本问题在表单的定义之内。表单不适用于模型字段,但需要表单字段。只有这样才能正确构建字段。
from django import forms
class OrderForm(forms.Form):
delivery_time = forms.CharField(max_length=100)
address_city = forms.CharField(max_length=40)
address_street = forms.CharField(max_length=40)
address_building = forms.CharField(max_length=40)
之后,尝试在模板中输出
{{ form }}
。 <form action="foo" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="submit"/>
</div>
关于django - form.cleaned_data返回空集,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29869780/