gpt4 book ai didi

django - form.cleaned_data 返回空集

转载 作者:行者123 更新时间:2023-12-02 11:40:55 24 4
gpt4 key购买 nike

我有一个表格:

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模型绑定(bind),但我的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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com