Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Make a form constructor like that
- ## in forms.py
- class Your_Form(forms.ModelForm):
- class Meta:
- model = Your_Model
- fields = [ 'city_id', 'user_id', ... ]
- def __init__(self, *args, city_id, user_id, **kwargs):
- ## put variables between args and kwargs otherwise you will get an error
- ## Don't forget to use it in views.py like this
- #(
- # form=Your_Form(request.POST, city_id=city_id,
- # user_id=user_id)
- #)
- ## also it is good to pass a variable in your URL if you want
- # self.Your_FORM_FIELD = city_id
- self.city = city_id
- self.user = user_id
- super(Your_Form, self).__init__(*args, **kwargs)
- var = YourModel.objects.get(city_id=self.city_id)
- # Assuming that you have 'role' CharField as choice field in your (User or CustomUser model)
- # with ('admin', 'manager', 'employee', 'customer')
- if self.user.role == 'admin': # make a condition to filter
- var = YouModel.objects.all()
- var2 = ''
- var3 = ''
- else:
- var = YourModel.objects.get(user_id=self.user)
- var2 = Another_Model.objects.get(user_id=self.user)
- ## var.get_preparation_period(),
- # "get_preparation_period()" it is a method from the models.py, use it as follows.
- var3 = var2.get_preparation_period()
- self.fields['city'].queryset = var
- self.fields['another_field'].widget.attrs['value'] = var3 # if you want to make a default value for this field
- self.fields['another_field'].widget.attrs['value'] = var2
Add Comment
Please, Sign In to add comment