在Django框架中,可以通過(guò)自定義ActionForm
來(lái)設(shè)置驗(yàn)證規(guī)則。以下是一個(gè)簡(jiǎn)單的示例,展示了如何自定義ActionForm
的驗(yàn)證規(guī)則:
django.forms.Form
或django.forms.ModelForm
。在這個(gè)例子中,我們將創(chuàng)建一個(gè)繼承自django.forms.Form
的自定義表單類。from django import forms
class CustomActionForm(forms.Form):
field1 = forms.CharField(max_length=100)
field2 = forms.IntegerField()
clean_field1()
和clean_field2()
方法來(lái)自定義字段的驗(yàn)證邏輯。在這些方法中,可以調(diào)用super().clean_field()
來(lái)執(zhí)行默認(rèn)的驗(yàn)證,然后根據(jù)需要添加自定義的驗(yàn)證邏輯。from django import forms
from django.core.exceptions import ValidationError
class CustomActionForm(forms.Form):
field1 = forms.CharField(max_length=100)
field2 = forms.IntegerField()
def clean_field1(self):
data = self.cleaned_data['field1']
# 添加自定義驗(yàn)證邏輯
if "bad_word" in data.lower():
raise ValidationError("Invalid input")
return data
def clean_field2(self):
data = self.cleaned_data['field2']
# 添加自定義驗(yàn)證邏輯
if data < 0:
raise ValidationError("Invalid input")
return data
from django.shortcuts import render
from .forms import CustomActionForm
def my_view(request):
if request.method == 'POST':
form = CustomActionForm(request.POST)
if form.is_valid():
# 處理表單數(shù)據(jù)
pass
else:
form = CustomActionForm()
return render(request, 'my_template.html', {'form': form})
{{ form }}
標(biāo)簽渲染表單。<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
通過(guò)以上步驟,你已經(jīng)成功地自定義了ActionForm
的驗(yàn)證規(guī)則。當(dāng)用戶提交表單時(shí),Django會(huì)執(zhí)行你在自定義表單類中定義的驗(yàn)證邏輯。如果驗(yàn)證失敗,將顯示相應(yīng)的錯(cuò)誤消息。