我找到了一些方法,但在从表单中提取数据方面遇到了麻烦。下面是我的表单及其post()方法。验证工作正常,但如何在app引擎的django版本中获取“清理”数据?
def get_type():
return [(str(type.key()), type.name) for type in GreType.all()]
class LatField(forms.Field):
def clean(self,value):
x = None
try:
x = float(value)
if x > 90.0 or x < -90.0:
x = None
except:
x = None
if x is None:
raise forms.ValidationError("Latitude should be a number between 90.00 and -90.00")
class LonField(forms.Field):
def clean(self,value):
x = None
try:
x = float(value)
if x > 180.0 or x < -180.0:
x = None
except:
x = None
if x is None:
raise forms.ValidationError("Longitude should be a number between 180.00 and -180.00")
class LocationForm(forms.Form):
type = forms.ChoiceField(choices=get_type())
name = forms.CharField(max_length=100)
desc = forms.CharField(widget=forms.Textarea(), required=False)
lat = LatField()
lon = LonField()
class LocationHandler(webapp.RequestHandler):
def get(self):
template_data = { 'form' : LocationForm() }
template_path = os.path.join(os.path.dirname(__file__), '../template/location.html')
self.response.headers['Content-Type'] = 'text/html'
self.response.out.write(template.render(template_path, template_data))
def post(self):
data = LocationForm(data=self.request.POST)
if data.is_valid():
# what to do here?
self.redirect('/locations')
我的验证例程可能有一些冗余,但我不清楚python范围
我传递了一个基于模型的表单(earlier question)来获取单独的lat和lon字段。)
答案 0 :(得分:0)
self.cleaned_data
中提供的已清理数据。这个例子工作正常:
class BlogCreateForm(forms.ModelForm):
class Meta:
model = Blog
exclude = ('author',)
def clean_slug(self):
'''Prevent duplicate blogs with equal key names'''
# blog with given url address already exists
if self.Meta.model.get_by_key_name(self.cleaned_data['slug']):
raise forms.ValidationError("Blog with url '%s' already exists" %
self.cleaned_data['slug'])
return self.cleaned_data['slug']
如果您使用内置版return self.cleaned_data['slug']
,请将return self.clean_data['slug']
替换为Django
。
尝试使用专为 Google App Engine设计的http://gaeframework.com - Python 网络框架