Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda