Django:创建一个不设置每个必需模型字段的表单?
使用 django/appengine,如何呈现一个允许输入某些模型字段的表单,然后在代码中设置其他模型字段。调用 form.save(commit=False) 会引发异常,因为未设置 user。 Django 处理此类情况的正确方法是什么?
我有以下模型和表单类:
class FooModel(db.Model):
user = db.UserProperty(required=True)
date = db.DateProperty(required=True)
class FooForm(djangoforms.ModelForm):
class Meta:
model = models.FooModel
exclude = ['user']
以及以下请求处理程序代码:
if request.method == 'POST':
form = forms.FooForm(request.POST)
# form.save() raises an exception because 'user' is not set
foo = form.save(commit=False)
foo.user = users.get_current_user()
foo.save()
Using django/appengine, how can I present a form which allows entry of certain model fields, and then set additional model fields in code. Calling form.save(commit=False) raises an exception because user is not set. What the correct Django way to handle cases such as this?
I have the following model and form classes:
class FooModel(db.Model):
user = db.UserProperty(required=True)
date = db.DateProperty(required=True)
class FooForm(djangoforms.ModelForm):
class Meta:
model = models.FooModel
exclude = ['user']
And the following request handler code:
if request.method == 'POST':
form = forms.FooForm(request.POST)
# form.save() raises an exception because 'user' is not set
foo = form.save(commit=False)
foo.user = users.get_current_user()
foo.save()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要匹配 SDK 示例,您可以省略
required=True 来自您的 UserProperty。
To match the SDK example, you could omit
required=True
from your UserProperty.