Bentley4
Bentley4

Reputation: 11038

How can I pass the current user to a custom form validator?

Two scoops of Django advises to make a custom validator for a form as follows:

class MyModel(models.Model):
    body = models.TextField()
    repo_name = models.CharField(max_length=50)


def validate_repo_existance(value):
     # Validate repo existance.
     # This needs the Github account which is bound 
     # to the user account though.


class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields["repo_name"].validators.append(validate_repo_existance)

    class Meta:
         model = MyModel

Is there any way to pass the user that is on the form page to the custom validator?

Upvotes: 2

Views: 1381

Answers (3)

Bentley4
Bentley4

Reputation: 11038

This is what I was looking for:

views.py

form = MyModelForm(request.user)  # when unbound

form = MyModelForm(request.user, data=request.POST)  # when bound

validators.py

class RepoValidator(object):
    def __init__(self, user):
        self.user = user

    def __call__(self, value):
        #self.user and value are accessible from here

forms.py

class MyModelForm(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields["repo_name"].validators.append(RepoValidator(user))

    class Meta:
         model = MyModel

Upvotes: 4

waverider
waverider

Reputation: 318

class MyModelForm(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields["repo_name"].validator.append(validate_repo_existance)

And pass the user from your view where you instantiate the form:

form = MyModelForm(request.user)  # when unbound

form = MyModelForm(request.user, data=request.POST)  # when bound

This pattern is used for any other data that you need to pass to a Django form.

Upvotes: 1

Chris Clouten
Chris Clouten

Reputation: 1085

The current user is stored in the request object, and can be accessed with request.user. You can pass this user as an argument into the form.

Upvotes: 1

Related Questions