models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=32)
class Article(models.Model):
author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True)
content = models.TextField()
forms.py
from django import forms
from .models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ['content']
在我的Web应用程序中,作者登录并撰写文章。很明显,当作者被提交ArticleForm时,他/她不需要填写ArticleForm中的作者字段,因为应用程序已经通过使用会话变量知道作者是谁。
这是我尝试添加作者的方式:
views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from .models import Article
from .forms import ArticleForm
@login_required
def new_article(request):
author_name = request.session['author_name']
author = Author.objects.get(name=author_name)
if request.method == 'POST':
form = ArticleForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.author = author # I suspect the mistake is here
# I also tried form.author = author.id
form.save()
return redirect('success')
else:
form = ArticleForm()
return render(request, 'writings/new_article.html', {'form': form})
当我查看数据库表时,author_id列始终为NULL
。我的做法有什么问题?如何在保存ModelForm之前添加模型关系?
答案 0 :(得分:1)
捕获从form.save(commit=False)
返回的对象并修改它而不是表单。 EG:
if form.is_valid():
article = form.save(commit=False)
article.author = author
article.save()
return redirect('success')