Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

116
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda