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.