我正在使用flask并且需要类似django的形式,因此在烧瓶视图中我可以简单地实例化一个类并检查它的有效性。这样的事情。
class StringField(object):
def __init__(self, value=None, null=False):
self.value = value.strip() if value is not None else value
self.nullable = nullable
def clean(self):
if self.null:
if self.value in ('', None):
return self.value
else:
if self.value in ('', None):
raise Exception(
"Value can not be null or blank"
)
try:
self.value = str(self.value)
except:
raise Exception(
"Value is neithe string nor can be coerced into one"
)
class MyForm(Form):
username = StringField(null=True)
在我的观点中,我想要这样做
mf = MyForm(data_dict)
if mf.is_valid():
# do something...
问题是: 如何在我们的主要Form类(一个继承的)的构造函数中获取所有字段,如用户名,电子邮件等,以便我可以对其属性应用一些验证,因为这些字段的数量可以变化
答案 0 :(得分:1)
Django的文档包含很多关于表单的信息,启动here。
例如:
from django import forms
# your form:
class UserForm(forms.Form):
username = forms.CharField(max_length=100)
email = forms.EmailField(null=True, blank=True)
# and your view:
def user_view(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = Userorm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = UserForm()
return render(request, 'user.html', {'form': form})
有关详细信息,请参阅上面的链接。