Django中的form,好像有一个form_for_instance方法,编辑form时可以从现成的实例生成。不过,我今天搜了半天都是只看见有人提问的,没有找到有人示范怎么使用的,我在Django1.02的包里好像也没有找到这个方法。
既然是Google的东西,我还是参考了GAE的文档,《The Django Form Validation Framework on Google App Engine》,看看在Google的默认框架是怎么调用的。
我仿照改成了我的Django代码,果然好使。我的代码如下:
models.py
class Config(db.Model):
author = db.UserProperty()
blog_title = db.StringProperty(default = ‘Blog’)
forms.py
class ConfigForm(djangoforms.ModelForm):
class Meta:
model = Config
exclude = [‘author’]
views.py
@admin_required
def blog_setting(request):
author = users.get_current_user()
try:
forminstance = Config.gql("WHERE author = :author",author=author)[0]
bInit = True
except:
bInit = False
if request.method == ‘GET’:
if bInit:
form = ConfigForm(instance=forminstance)
else:
form = ConfigForm()
if request.method == ‘POST’:
if bInit:
form = ConfigForm(request.POST,instance=forminstance)
else:
form = ConfigForm(request.POST)
if form.is_valid():
config = form.save(commit=False)
config.author = author
config.put()
return HttpResponseRedirect(’/’)#要重定向到别的页面去的,防止重刷
else:
pass
return render_to_response(‘blog/blog_setting.html’, {‘form’: form}, context_instance=RequestContext(request))
GAE中使用Django的Form
GAE中使用Django的Form
...