Search code examples
djangodjango-formsdjango-widget

Django model-forms widget choice based on URL variables


lets say I have a form based on the model:

Form1:
class Meta:
    model = Comment
        widgets = {"field1": forms.HiddenInput } # option 1
#or 
    widgets = {"field2": forms.HiddenInput } # option 2

And I have 2 widgets options . First -displays 2nd field but hides 1st and second -other way around. Choice of option 1 or option 2 is based on what ‘key’ variable it would receive from URL kwargs. For example if key == 1 then option 1 is chosen, if key == 2 – then second option is chosen.

#example

<a href="{%  url "app:route" key="1 or 2 " pk=object.pk %}"> COMMENT</a>

Question is how to reach self.kwargs dictionary in .forms? Or there is an alternative less dumb way to do it? Final goal is to use one of the options , base oneself on the “key” variable , that is different urls would send different “key = x “ variables.

Where I could implement this sort of logic in Django? Views?


Solution

  • You need to send your form the information on which url is accessed, then you can use this information to choose which widget you want to use.

    Change the __init__ of your form:

    #forms.py
    
    class Form1(ModelForm):
        def __init__(self, key, *args, **kwargs):
            super(Form1, self).__init__(*args, **kwargs)
            if key == 1:
                self.fields['field1'].widget = forms.HiddenInput()  # option 1 HiddenInput() 
            else:
                self.fields['field2'].widget = forms.HiddenInput()  # option 2 HiddenInput() 
    
        class Meta:
            model = Comment
    

    Then, in your view, add the key from request's kwargs in form's kwargs

    # views.py
    
    class MyFormView(FormView):
        form_class = Form1
    
        def get_form_kwargs(self):
            kwargs = super(MyFormView, self).get_form_kwargs()
            kwargs['key'] = self.kwargs.get('key')
            return kwargs