为什么django表单变量是静态成员而不是实例成员

时间:2016-05-26 03:49:34

标签: django django-forms

我目前有一个看起来像这样的表单对象

class MainLoginForm(forms.Form):
    PART_CHOICES = (
        ("0", "0"),
        ("1", "1"),
    )

    user_name = forms.CharField(required=True)
    user_category = forms.ChoiceField(choices=PART_CHOICES)
    user_password = forms.CharField(widget=forms.PasswordInput,required=True)

然后我在视图中以下列方式使用此对象

def home(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        form = MainLoginForm(request.POST)
        if form.is_valid():
            return HttpResponse('Hello World')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = MainLoginForm()

    return render(request, 'main/home.html', {
        'form': form,
    })

一切似乎都有效,除了我很好奇为什么我创建的对象有类成员而不是像这样的实例成员?我刚开始学习Django并且很好奇......

class MainLoginForm(forms.Form):
        PART_CHOICES = (
            ("0", "0"),
            ("1", "1"),
        )
        def __init__(self)
        self.user_name = forms.CharField(required=True)
        self.user_category = forms.ChoiceField(choices=PART_CHOICES)
        self.user_password = forms.CharField(widget=forms.PasswordInput,required=True)

当多个同时发出的请求进入时,当前的方式不安全吗?

1 个答案:

答案 0 :(得分:1)

以下语法称为声明性语法

class MainLoginForm(forms.Form):
    user_name = forms.CharField(required=True)

您可以查看forms.Form

中的评论
class Form(six.with_metaclass(DeclarativeFieldsMetaclass, BaseForm)):
      "A collection of Fields, plus their associated data."
      # This is a separate class from BaseForm in order to abstract the way
      # self.fields is specified. This class (Form) is the one that does the
      # fancy metaclass stuff purely for the semantic sugar -- it allows one
      # to define a form using declarative syntax.
      # BaseForm itself has no way of designating self.fields.

您必须注意,您在上述表单中定义的字段仅在self.fields['user_name']中可用,而不是直接在self.user_name self指的是表单实例。

DeclarativeFieldsMetaclass负责读取使用声明性语法定义的字段,然后在表单实例上填充self.fields

  

当多个同时发出的请求进入时,当前的方式不安全吗?

不安全的意思并不完全清楚,因为这里非常主观。但是,如果您只是意味着在类级别定义了字段,那么您可以在上面的解释中看到情况并非如此。因此,从这个角度来看,目前的方法是安全的。

如果您确实希望创建一个需要在__init__方法中定义字段的表单,则必须将字段存储在dict中并更新self.-fields集合:

class MainLoginForm(forms.Form):

     def __init__(self, *args, **kwargs):
         super(MainLoginForm, self).__init__(*args, **kwargs)

         # create a new field 
         self.fields['user_name'] = forms.CharField(required=True)