Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
How to access the request object in FormView

I want to access the request object in FormView and get client IP. As we all know, it's not very reliable to put a hidden-field in the html form because it can be changed by user if user wants do so. Therefore, I choose to do it in the backed. I use ModelForm as the form_class of FormView and exclude the ip field in the form. Here come the problem, I do know how to add the ip field dynamically. I always can't save the model successfully. Here is my code.

models.py

class MyModel(models):
    ip = models.GenericIPAddressField()
    [...]

forms.py

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        exclude = ['ip']

views.py

class MyView(FormView):
    form_class = MyForm
    [...]

I've tried to change the psot() method and manually added the ip field of request.POST but I just found that I didn't know how to pass the form instance..I spent all night to solve this problem and finally I failed .. Tanks for helping in advance..

Thanks Daniel for answering this question.

I changed my code into this:

views.py

class PollView(FormView):
    template_name = 'poll.html'
    form_class = PollForm
    success_url = '/thanks/'

    def get_ip(self,request):
        if request.META.has_key('HTTP_X_FORWARDED_FOR'):  
            ip =  request.META['HTTP_X_FORWARDED_FOR']  
        else:  
            ip = request.META['REMOTE_ADDR']
        return ip

    def form_valid(self, form):
        form.instance.ip = self.get_ip(self.request)
        super(PollView,self).form_valid(form)

but I got an error:

ValueError at /
The view poll.views.PollView didn't return an HttpResponse object. It returned None instead.
about 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!