Django表单自定义:更改其他字段更改字段

时间:2016-03-30 11:42:38

标签: python django forms django-forms

我在Django只有几天的新手。现在,当自定义表单中其他字段的值发生变化时,我需要在一个字段中更改值和表示。此时,更改MyModel 限制

的myapp / models.py:

class MyModel(models.Model):
    somefield = models.IntegerField(default=0)

的myapp / forms.py

class MyModelForm(models.Model):
    someformfield = models.BooleanField(required=False)
    // Here it should be smth as following:
    // def clean(..), or def save(..), or def __init__(..)
    if MyModelForm.is_valid():
        # This if-else construction further should 'raise' on every change of 'someformfield'-checkbox:
        if someformfield == True:
            somefield = 0
            self.fields['somefield'].widget = forms.HiddenInput()
        else:
            somefield = data['somefield'] # Just to use User Input
            self.fields['somefield'].widget = forms.ShownInput() # What's wrong, but I just need to abort HiddenInput somehow - so, how shoulda do it?

我尝试定义了clean(),如下所示,但它没有做任何事情,甚至没有提出form.ValidationError:

def clean(MyModelForm, self):
    cleaned_data = super(MyModelForm, self).clean()

    if self.cleaned_data['someformfield']:
        if self.cleaned_data['somefield'] != 0:
            # This didn't work
            raise forms.ValidationError(
                "Error!"
            )
            # And following also didn't work
            self.cleaned_data['somefield'] = 0
            self.fields['somefield'].widget = forms.HiddenInput()

这也不起作用:

def clean(MyModelForm, self):
    cleaned_data = super(MyModelForm, self).clean()
    somefield = cleaned_data.get("somefield")
    someformfield = cleaned_data.get("someformfield")

        if someformfield:
            # Also not working
            if somefield != 0:
                raise forms.ValidationError(
                    "Error!"
                )
            # Also not working
            somefield = 0
            self.fields['somefield'].widget = forms.HiddenInput()

也许,我应该使用其他一些方法 - 保存(..)或 init (..),或者其他什么,但在文档中完全混淆并且不知道,目的是什么这些方法中的每一种。那么我应该在这里使用哪种方法以及如何使用?

1 个答案:

答案 0 :(得分:1)

clean方法只能接受一个self的参数。

class MyModelForm(models.Model):
    someformfield = models.BooleanField(required=False)

    def clean(self):
        cleaned_data = self.cleaned_data
        # do the work you want ...