Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Banned IPs in Django form validation

I am trying to validate a form, such that if IP of user (request.META['REMOTE_ADDR']) is in a table BlockedIPs, it would fail validation. However I don't have access to request variable in Form. How do I do it? Thanks.

like image 305
pitr Avatar asked Feb 18 '09 10:02

pitr


1 Answers

Make it available to your form by overriding __init__ so it can be passed in during construction (or you could just pass the IP itself):

from django import forms

class YourForm(forms.Form)
    # fields...

    def __init__(self, request, *args, **kwargs):
        self.request = request
        super(YourForm, self).__init__(*args, **kwargs)

    # validation methods...

Now you just need to pass the request object as the first argument when initialising the form and your custom validation methods will have access to it through self.request:

if request.method == 'POST':
    form = YourForm(request, request.POST)
    # ...
else:
    form = YourForm(request)
# ...
like image 128
Jonny Buchanan Avatar answered Sep 18 '22 10:09

Jonny Buchanan