I have a form, where validation depends on logged user. For some users are certain values valid, for other users they are invalid. What is valid and what is invalid is dynamic - I can't create new form for each user group.
What's more I need this same validation in more forms, so I created custom form field. To this custom form field I need to pass user instance somehow to check if the value is valid or not.
How to do this?
I am doing it like that:
class EventForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
# doing stuff with the user…
super(EventForm, self).__init__(*args, **kwargs)
In your view class/method you have to instantiate the form like this:
form = EventForm(user=request.user, data=request.POST)
You don't need an extra field for this.
You can access the current user by passing it explicitly or by fetching it from the request in your form's init()
method.
Then you can use the retrieved value when cleaning your form.
If you need this functionality in several forms I'd create either a base class that the specialized forms inherit from or create a mixin that adds the desired functionality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With