我创建了一个“香草”表单,提交后应根据文本输入检查是否存在某项。如果确实如此,则会在该项目的“ item_selected”字段上增加一个计数器,然后继续使用该项目和其余提交字段创建请购记录。其他项目不存在,它将创建项目记录以及创建请购单记录。提交我的表格时,没有任何反应。我确保url路由正确并且正在提交到正确的视图。
我不相信我可以使用ModelForm,因为ModelForms绑定到一个模型,在这里我试图更新多个表。预先谢谢你!
Views.py
def create_req(request):
if request == 'POST':
req_form = ReqForm(request.POST)
if req_form.is_valid():
try:
item_record = ItemMaster.objects.get(item=req_form.cleaned_data['item'])
item_record.save(commit=False)
item_record.item_selected = F('item_selected') + 1
item_record.save()
requisition_record = Requisition.objects.create(item=req_form.cleaned_data['item'],
signature=req_form.cleaned_data['signiture'])
requisition_record.save(commit=False)
requisition_record.username = CustomUser.objects.get(username=request.user)
requisition_record.save()
except ItemMaster.DoesNotExit:
item_record = ItemMaster.objects.create(item=req_form.cleaned_data['item'],
description=req_form.cleaned_data['description'],
price=req_form.cleaned_data['price'],
item_selected=1)
item_record.save()
requisition_record = Requisition.objects.create(item=req_form.cleaned_data['item'], signature=req_form.cleaned_data['signiture'])
requisition_record.save(commit=False)
requisition_record.username = request.user
requisition_record.save()
return HttpResponseRedirect(reverse('home') )
else:
req_form = ReqForm()
return render(request, 'req/create_req.html', {'req_form':req_form})
forms.py
class ReqForm(forms.Form):
item = forms.CharField(min_length=3, max_length=20)
description = forms.CharField(min_length=0, max_length=50, empty_value='' )
price = forms.DecimalField(max_digits=19, decimal_places=2)
signiture = forms.CharField(min_length=0, max_length=10, empty_value='')
create_req.html
<p>
<a href="{% url 'home' %}">Home</a>  
<a href="{% url 'requisition:create_req' %}">Reset Form</a>
</p>
<h1>Example Form</h1>
{% if error_message %}
<p>
<strong>{{error_message}}</strong>
</p>
{% endif %}
<body>
<form method="post" action="{% url 'requisition:create_req' %}" >
{% csrf_token %}
{{ req_form }}
<input type="submit" value="Submit">
</form>
</body>
Urls.py
app_name = 'requisition'
urlpatterns = [
path('', views.create_req, name='create_req'),
]
答案 0 :(得分:1)
更改
if request == "POST":
...
到
if request.method == "POST":
...