0

我想做的是这样的:

1)我已经创建了模型

class Example(models.Model):

     username = models.CharField(max_lenght=111)
     pass = models.CharField(max_lenght=111)

2)我使用 ModelForm 创建了表单,并添加了一个额外的字段

class ExampleForm(ModelForm):

    extra_field= form.CharField(max_length=333)

    class Meta:
        model = Client
        fields = ['username', 'pass']

3)我创建了视图来处理这个表单

class Registration(CreateView):
    """
    View handles user registration.
    """
    form_class = ExampleForm
    model = Example
    template_name = 'accounts/registration.html'
    success_url = reverse_lazy('accounts:registered')

现在我想做的是对extra_field进行一些自定义处理。我发现这应该在 ExampleForm 的保存方法中完成。例如:

 def save(self, commit=True):

        user = super(ExampleForm, self).save(commit=False)
        data = self.cleaned_data['extra_field']
        user.set_password(self.cleaned_data['pass'] + self.cleaned_data['extra_field'])

        if commit:
            user.save()
        return user

但这不起作用。这是处理这种情况的正确方法,还是有更好的方法?最大的问题是这不是我的代码,所以我应该只更改 ExampleForm。有没有办法做到这一点?

提前致谢。

最好的问候,尼古拉

4

1 回答 1

1

您可以form_valid()CreateView.

class Registration(CreateView):
    """
    View handles user registration.
    """
    form_class = ExampleForm
    model = Example
    template_name = 'accounts/registration.html'
    success_url = reverse_lazy('accounts:registered')

    def form_valid(self, form):
        example = form.save(commit=False)
        example.extra_field = derive_data(form.cleaned_data)
        example.save()
        return super(Registration, self).form_valid(form)
于 2013-07-20T16:02:39.880 回答