开发者

Late Formfield cleaning - clean Formfield within Form subclass

开发者 https://www.devze.com 2023-02-19 17:29 出处:网络
I have two ModelFields (Char and Decimal) and it would be trivial to clean them separately with the clean_formfield() method. But instead to display both formfields, I\'d like to display just one inpu

I have two ModelFields (Char and Decimal) and it would be trivial to clean them separately with the clean_formfield() method. But instead to display both formfields, I'd like to display just one input field in combination with a ChoiceField where the user can decide whether the next input will be some words or a number. The split is necessary because I'd like to do some aggregation with the numbers later on.

It's obvious that I can't use clean_formfield() because of dependency, so it has t开发者_StackOverflowo go into the form cleaner. The question is how to realize a 'late Formfield cleaning'?

class Input(models.Model):
   ...
   number = models.DecimalField()
   word = models.CharField()
   ...

class InputForm(forms.ModelForm):
   ...
   type = forms.CharField(widget=forms.RadioSelect(choices=(('word','Word'),('number','Number'),)))
   input = forms.CharField()
   ...
   def clean(self):
      cleaned_data = self.cleaned_data
      type = cleaned_data.get('type')
      input = cleaned_data.get('input')

    if type == 'number':           
        <<< clean_Decimal_Formfield >>>
        cleaned_data['number'] = input
        cleaned_data['word'] = None
    else:
        <<< clean_Char_Formfield >>>        
        cleaned_data['number'] = None
        cleaned_data['word'] = input

    return cleaned_data


I would stick with this, 1 model field = 1 form field. If you need to save only one field (number or text) you can hide/show the two fields based on the radio select state (trivial js)

In order to prevent one to save both values than in the clean of the form you can check that only one field is filled and that one is compatible with the radio selection.


It's not necessary to invent a new method for 'Late FormField cleaning'! Just do it like this:

...
if type == 'number':           
    cleaned_data['number'] = input
    cleaned_data['word'] = None
else:
    cleaned_data['number'] = None
    cleaned_data['word'] = input
...
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号