Django模型自动设置字段

发布于 2024-11-04 11:30:00 字数 509 浏览 0 评论 0原文

我有一个允许用户发布文章的表单。文章表与用户表链接在一起,因此我需要根据撰写者设置 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

少女七分熟 2024-11-11 11:30:00

假设您确保用户已登录。

models.py:

Article(models.Model):
    text = modesl.TextField()
    user = models.ForeignKey(User)

forms.py:views.py

ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        exclude = ('user',)

:

article = Article(user=request.user)   

if request.method == 'POST':
    form = ArticleForm(request.POST, instance=article)
    if form.is_valid():
        form.save()
        return HttpResponse('success')
else:
    form = ArticleForm(instance=article)

在保存之前设置数据的另一种方法是使用:

if form.is_valid():
    art = form.save(commit=False)
    art.user = request.user
    art.save()
    return HttpResponse('Success')

Assuming that you are making sure the user is signed in.

models.py:

Article(models.Model):
    text = modesl.TextField()
    user = models.ForeignKey(User)

forms.py:

ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        exclude = ('user',)

views.py:

article = Article(user=request.user)   

if request.method == 'POST':
    form = ArticleForm(request.POST, instance=article)
    if form.is_valid():
        form.save()
        return HttpResponse('success')
else:
    form = ArticleForm(instance=article)

Another way to set data before saving is to use:

if form.is_valid():
    art = form.save(commit=False)
    art.user = request.user
    art.save()
    return HttpResponse('Success')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文