Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get request in form field validation

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?

like image 926
Tom Tichý Avatar asked Feb 16 '23 19:02

Tom Tichý


2 Answers

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)
like image 126
toabi Avatar answered Feb 23 '23 16:02

toabi


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.

like image 34
arie Avatar answered Feb 23 '23 14:02

arie