0
models.py添加模型有關的ModelForm節約
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之前添加模型關係?