我創建了一個帶有多個輸入欄位的 POST Django 表單。其中許多是必需的,并且它們會在網站渲染中拋出所需的錯誤。即使我指定他們將錯誤扔到下面的塊中,他們也會在上面拋出錯誤。請幫忙。
表格定義
class Install_Version_Form(forms.Form):
project = forms.CharField(widget=forms.TextInput(
attrs={'class': 'textInputAddMach', 'placeholder': "project"}), max_length=100, required=True)
privacy = forms.ChoiceField(choices=privacy, required=True)
iteration = forms.CharField(widget=forms.TextInput(
attrs={'class': 'textInputAddMach', 'placeholder': "iteration"}), max_length=100, required=True)
machine_name = forms.CharField(widget=forms.TextInput(
attrs={'class': 'textInputAddMach', 'placeholder': "machine name"}), max_length=100, required=True)
version = forms.CharField(widget=forms.TextInput(
attrs={'class': 'textInputAddMach', 'placeholder': "e.g. 0.1"}), max_length=100, required=True)
def __init__(self, *args, **kwargs):
super(Install_Version_Form, self).__init__(*args, **kwargs)
def clean(self):
cleaned_data = super().clean()
表格視圖 CTX 包裝
def installation(request):
ctx = {
"installVersionForm": None
}
ctx["installVersionForm"] = Install_Version_Form(request.POST)
if request.method == 'POST':
form = Install_Version_Form(request.POST)
if form.is_valid():
(contact cloud)
else:
ctx["installVersionForm"] = form
return render(request, "installation.html", ctx)
HTML 模板
{% block extend_content %}
<form action="" method="post">
{% csrf_token %}
{{installVersionForm.as_p}}
<input type="submit" value="add new version">
</form>
<br/>
<br/>
<br/>
{% if installVersionForm.errors %}
{% for error in installVersionForm.errors %}
<small>{{ error }}</small>
{% endfor %}
{% endif %}
{% if installVersionForm.messages %}
{% for message in installVersionForm.messages %}
<small>{{ message }}</small>
{% endfor %}
{% endif %}
{% endblock %}
uj5u.com熱心網友回復:
當您第一次創建表單實體時,您不必提供 request.POST。如果你這樣做了,它會處理事情,就好像它是由你的用戶填寫的一樣,即使它不是。
def installation(request):
ctx = {
"installVersionForm": None
}
ctx["installVersionForm"] = Install_Version_Form() <=====
if request.method == 'POST':
form = Install_Version_Form(request.POST)
if form.is_valid():
(contact cloud)
else:
ctx["installVersionForm"] = form
return render(request, "installation.html", ctx)
為了有一些干凈的東西,我會這樣做:
def installation(request):
if request.method == 'GET':
ctx = {
"installVersionForm": Install_Version_Form()
}
if request.method == 'POST':
form = Install_Version_Form(request.POST)
if form.is_valid():
(contact cloud)
else:
ctx = {
"installVersionForm": Install_Version_Form(request.POST)
}
return render(request, "installation.html", ctx)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/522443.html
下一篇:如何更改下拉選項的值屬性?
