Django模型自动设置字段
我有一个允许用户发布文章的表单。文章表与用户表链接在一起,因此我需要根据撰写者设置 user_id 字段。通常,django 表单会显示一个下拉菜单,让我选择作者,但用户的情况并非如此。
I have the following code:
if request.method == 'POST':
ArticleForm = ArticleForm( request.POST )
if ArticleForm.is_valid():
article = ArticleForm.save ()
return render( request, 'success.html' )
else:
ArticleForm = ArticleForm()
return render( request, 'post.html', {'ArticleForm': ArticleForm} )
如何在验证请求之前设置一个字段,该字段将失败,因为某些字段应该由代码设置而不是基于请求数据?
I have a form allowing users to post an article. The article table is chained with the users table so, I need to set the user_id field based on who's writing. Normally, django form will display a drop down to allow me to select the author but that's not the case for the user.
I have the following code:
if request.method == 'POST':
ArticleForm = ArticleForm( request.POST )
if ArticleForm.is_valid():
article = ArticleForm.save ()
return render( request, 'success.html' )
else:
ArticleForm = ArticleForm()
return render( request, 'post.html', {'ArticleForm': ArticleForm} )
How do I set a field before validating the request which will fail in case not since certain fields are supposed to be set by the code and not based on request data?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您确保用户已登录。
models.py:
forms.py:views.py
:
在保存之前设置数据的另一种方法是使用:
Assuming that you are making sure the user is signed in.
models.py:
forms.py:
views.py:
Another way to set data before saving is to use: