在Django Web框架中开发网站期间,验证表单时出现表单无效错误。
我已经在网上搜索解决方案,但无法解决我的问题。
我的文件如下。
models.py
class Customer(models.Model):
f_name = models.CharField(max_length = 30, null=True)
last_name = models.CharField(max_length = 30, null= True)
cont_no = models.CharField(max_length = 30, null= True)
pincode = models.IntegerField(default=0)
def __str__(self):
return self.f_name
class Product(models.Model):
name = models.CharField(max_length = 30, null= True)
uniq_price = models.IntegerField(default=0)
def __str__(self):
return self.name
class Order(models.Model):
cust_name = models.ForeignKey(Customer,related_name='first_name', on_delete=models.CASCADE)
prod_name = models.ForeignKey(Product, related_name='uniqe_price', on_delete=models.CASCADE)
unit_price = models.IntegerField(default=0)
quantity = models.IntegerField(default=0)
total = models.IntegerField(default=0)
表格
class CustomerForm(forms.ModelForm):
class Meta:
model = Order
fields = "__all__"
views.py
def add_order(request):
if request.method == "POST":
form = CustomerForm(request.POST)
form.save()
return redirect("place_ord")
else:
form = CustomerForm()
home.html
<form id="myForm" action="{% url 'add_order' %}" method="POST">
{% csrf_token %}
<h1>add order</h1>
<label>Customer</label>
<select id="custs" name="customer">
<option value="">Select Customer</option>
{% for cust in customers %}
<option id="{{ cust.id }}" value="{{ cust.f_name }}">
{{ cust.f_name }}
</option>
{% endfor %}
</select><br><br>
<label>Product</label>
<select id="singleSelectTextDDJS" name="prods" onchange="singleSelectChangeText()">
<option>Select Product</option>
{% for prod in products %}
<option value="{{ prod.uniq_price }}">
{{ prod.name }}
</option>
{% endfor %}
</select><br><br>
<label>Price:</label>
<input type="text" name="price" class="Pric" id="textFieldTextJS" readonly=""><br><br>
Qualitys:<input type="number" id="qty" class="qtys" name="quality"><br><br>
Total price:<input type="text" name="totals" class="totals" id="total" readonly="">
<br><br>
<button type="submit" name="submit">place order</button>
</form>
错误
File "C:\Python37\lib\site-packages\django\forms\models.py", line 453, in save
'created' if self.instance._state.adding else 'changed',
ValueError: The Order could not be created because the data didn't validate.
我无法验证我的表格,有人可以指导我我在做什么错吗?
问题在于您在表格中给出的选项。
value
应该是pk
那个对象的。前-
<select id="custs" name="customer">
<option value="">Select Customer</option>
{% for cust in customers %}
<option id="cust_{{ cust.id }}" value="{{cust.pk}}">
{{ cust.f_name }}
</option>
{% endfor %}
</select>
该值不与选择字段一起验证。尝试在所有选项中仅放入有效值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句