Django Forms.ModelForm不调用init方法

时间:2018-09-22 10:54:46

标签: django django-models django-forms

我不太了解django何时调用 init 方法... 我试图创建一个自定义用户模型,该模型在admin视图中可以正常工作。现在,我想添加一个用于用户注册的表格。表单现在看起来像这样:

class RegisterForm(forms.ModelForm):
def __int__(self, *args, **kwargs):
    super(RegisterForm, self).__int__(*args, **kwargs)  # EVT ERROR HIER
    self.fields['password1'] = forms.CharField(widget=forms.PasswordInput)
    self.fields['password2'] = forms.CharField(widget=forms.PasswordInput)
    print("STARTING FORM")

#password1 = forms.CharField(widget=forms.PasswordInput)
#password2 = forms.CharField(widget=forms.PasswordInput,)

class Meta:
    model = User
    fields = ('email', )

def clean_email(self):
    email = self.cleaned_data.get('email')
    qs = User.objects.filter(email=email)
    if qs.exists():
        #raise forms.ValidationError(_("Mail is allready taken"))
        pass
    return email

def clean_password2(self):
    password1 = self.cleaned_data.get("password1")
    password2 = self.cleaned_data.get("password2")
    if password1 and password2 and password1 != password2:
        #raise forms.ValidationError(_("Passwords don't match"))
        pass
    return password2

您可以在表格中看到,我尝试了一下。但是没有调用 init 方法内部的任何内容。我真的不明白为什么。我想使用脆皮形式,然后将辅助方法放入init方法中。拳头我认为这是一个脆皮的错误/错误。但是,即使没有调用print方法,我仍感觉到自己的init方法没有被调用。

在我得到的意见中:

class SignUpView(bracesviews.AnonymousRequiredMixin,
             bracesviews.FormValidMessageMixin,
             generic.CreateView):
form_class = RegisterForm
template_name = 'accounts/signup.html'
success_url = "/admin/"
form_valid_message = "YES"

def form_valid(self, form):
    r = super().form_valid(form)
    email = form.cleaned_data["email"]
    password = form.cleaned_data["password1"]
    user = auth.authenticate(email=email, password=password)
    auth.login(self.request, user)
    return r

在这里,我已经尝试了基于函数的视图,以及仅在FormView旁边不放置任何Mixins。到目前为止,什么都没做,我真的不明白为什么。

0 个答案:

没有答案