amr_aly

Filter_in_Forms

Jan 17th, 2022 (edited)
344
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.57 KB | None | 0 0
  1. ## Make a form constructor like that
  2. ## in forms.py
  3. class Your_Form(forms.ModelForm):
  4.    
  5.     class Meta:
  6.         model = Your_Model
  7.         fields = [ 'city_id', 'user_id', ... ]
  8.    
  9.     def __init__(self, *args, city_id, user_id, **kwargs):  
  10.         ## put variables between args and kwargs otherwise  you will get an error  
  11.         ## Don't forget to use it in views.py like this
  12.         #(
  13.         #   form=Your_Form(request.POST, city_id=city_id,                
  14.         #    user_id=user_id)
  15.         #)
  16.         ## also it is good to pass a variable in your URL if you want
  17.         # self.Your_FORM_FIELD = city_id
  18.         self.city = city_id
  19.          self.user = user_id
  20.  
  21.         super(Your_Form, self).__init__(*args, **kwargs)
  22.        
  23.         var = YourModel.objects.get(city_id=self.city_id)
  24.         # Assuming that you have 'role' CharField as choice field in your (User or CustomUser model)
  25.         # with ('admin', 'manager', 'employee', 'customer')
  26.         if self.user.role == 'admin':  # make a condition to filter
  27.             var = YouModel.objects.all()
  28.             var2 = ''
  29.             var3 = ''
  30.         else:
  31.             var = YourModel.objects.get(user_id=self.user)
  32.             var2 =  Another_Model.objects.get(user_id=self.user)
  33.             ## var.get_preparation_period(),
  34.             # "get_preparation_period()" it is a method from the models.py, use it as follows.
  35.             var3 = var2.get_preparation_period()
  36.  
  37.         self.fields['city'].queryset = var
  38.         self.fields['another_field'].widget.attrs['value'] = var3 # if you want to make a default value for this field
  39.         self.fields['another_field'].widget.attrs['value'] = var2
Add Comment
Please, Sign In to add comment