在 Django Web 框架中开发网站期间,我在验证表单时收到表单无效错误。
我在网上搜索了解决方案,但无法解决我的问题。
我的文件如下。
模型.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)
forms.py
class CustomerForm(forms.ModelForm):
class Meta:
model = Order
fields = "__all__"
View .py
def add_order(request):
if request.method == "POST":
form = CustomerForm(request.POST)
form.save()
return redirect("place_ord")
else:
form = CustomerForm()
首页.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>
该值未使用选择字段进行验证。尝试在所有选项中仅放置有效值。
关于python - 为什么我在 Django 中收到表单无效错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58501362/