Skip to main content
 首页 » 编程设计

python之Django 表单自定义 : change field on other field change

2025年04月02日49bhlsheji

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

我的应用程序/models.py:

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

我的应用程序/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(),但它什么也没做,甚至没有引发 forms.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() 

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

请您参考如下方法:

clean 方法应该只接受一个参数,即 self。

class MyModelForm(models.Model): 
    someformfield = models.BooleanField(required=False) 
 
    def clean(self): 
        cleaned_data = self.cleaned_data 
        # do the work you want ...