tags:

views:

38

answers:

2

What is the best way to have the IP address be included with the Form is_valid. Let me start with some code examples.

urls.py

from django.conf.urls.defaults import *
from testpost.views import TestPost

urlpatterns = patterns('',
    (r'^djtestforms/', TestPost),
)

model.py

from django.db import models

class TestPostModel(models.Model):
    name = models.CharField(max_length=100)
    comment = models.CharField(max_length=100)
    ip_address = models.IPAddressField()

    def __unicode__(self):
        return self.model

    @models.permalink
    def get_absolute_url(self):
        return ('TestPostModel', [self.id])

forms.py

from django import forms
from models import TestPostModel

class TestPostForm(forms.ModelForm):
    class Meta:
        model = TestPostModel

from forms import TestPostForm
from models import TestPostModel
from django.http import HttpResponse

def TestPost(request):
    f = TestPostForm(request.POST)
    if f.is_valid():
        object = f.save()
        return HttpResponse("That worked")
    else:
        return HttpResponse("That didn't work")

My question is when I try to do "f=TestPostForm(request.POST)" what is the best way to have the IP address added to TestPostForm. I was thinking of something along the lines of "f = TestPostForm(request.POST, ip_address=request.META["REMOTE_ADDR"])" but that doesn't work. Any suggestions?

A: 

Save with commit=False

form=TestPostForm(data=request.POST)
if form.is_valid():
  object=form.save(commit=False)
  object.ip_address=request.META['REMOTE_ADDR']
  object.save()

You will probably need to set blank=True in the model or required=False in the form for the form to validate

czarchaic
Since the reason this question was asked was to make the form valid, this code doesn't help at all. The answer below is the right one.
Mark0978
+2  A: 

@czarchaic - Your'e answer gave me a good hint on what to do. I changed the model so that blank=True for ip_address, and then did a

f = TestPostForm(request.POST)
f.data['ip_address']=request.META['REMOTE_ADDR']

After that is_valid worked. Thanks.

letsgofast