1

I would like to check the URL path so I can create the form base on it. In the view, we can use the request parameter to get the URL path, is there a similar way so we can get the current URL inside forms.py?

URL=??
if URL == 'phones':
      brand_choises= (('Sumsung', 'Sumsung'),
                     ('Iphon', 'Iphone'),)
if URL == 'cars':
      brand_choises= (('Honda', 'Honda'),
                     ('Toyota', 'Toyota'),)
class Productform(forms.ModelForm):
    brand=forms.ChoiceField(choices=brand_choises,widget=forms.Select(attrs={'class':'products'}))
    class Meta:
      model = Product

   def __init__(self, *args, **kwargs):
     super(ProductForm, self).__init__(*args, **kwargs)
     self.fields['brand'].choices = brand_choises
Fouad Selmane
  • 378
  • 2
  • 11
  • similar to [this](https://stackoverflow.com/questions/11645939/django-get-current-url-when-init-a-widget-in-form) – uedemir Oct 16 '18 at 07:29

1 Answers1

2

You can't do it like this. Anything at module level or class level is defined when the module is first imported, so cannot depend on the URL. The only thing you can do is to pass in a parameter when the form is instantiated, and change the choices based on that. You can use a dict to hold the choices so that the form can just pick the relevant one from the parameter:

CHOICE_DICT = {
  'phone': (
    ('Samsung', 'Samsung'),
    ('iPhone', 'iPhone'),
  )
  'car': (
    ('Honda', 'Honda'),
    ('Toyota', 'Toyota'),
  )
}

class Productform(forms.ModelForm):
    brand=forms.ChoiceField(choices=brand_choises,widget=forms.Select(attrs={'class':'products'}))
    class Meta:
      model = Product

   def __init__(self, *args, **kwargs):
     form_type = kwargs.pop('form_type', None)
     super(ProductForm, self).__init__(*args, **kwargs)
     self.fields['brand'].choices = CHOICE_DICT[form_type]

and then in your form you would do form = Productform(form_type='car') or whatever. Don't forget to pass it both on POST and GET.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Thank you sir for your answer, I follow your instruction and I get this error "__init__() got an unexpected keyword argument 'form_type'" – Fouad Selmane Oct 17 '18 at 02:55