将表格包含在表格is_valid中的最佳方法是什么。让我先从一些代码示例开始。
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")
我的问题是当我尝试“f = TestPostForm(request.POST)”时,将IP地址添加到TestPostForm的最佳方法是什么。我正在考虑“f = TestPostForm(request.POST,ip_address = request.META [”REMOTE_ADDR“])”的内容,但这不起作用。有什么建议吗?
答案 0 :(得分:2)
@czarchaic - 你的答案给了我一个很好的暗示,该做什么。我更改了模型,因此对于ip_address,blank = True,然后执行了
f = TestPostForm(request.POST)
f.data['ip_address']=request.META['REMOTE_ADDR']
之后is_valid有效。感谢。
答案 1 :(得分:-1)
使用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()
您可能需要在模型中设置blank=True
或在表单中设置required=False
以验证