擅长:python、mysql、java
<p>使用一个模型表单会使这个视图更加紧凑,但是在这种情况下,我会考虑对您的视图进行一些更改</p>
<p>像这样编辑视图</p>
<pre><code>def add_book(request):
if request.method == 'POST':
user = request.user
data = {
'title':request.POST.get('title'),
'content':request.POST.get('review'),
'rating':request.POST.get('rating'),
}
author_name = request.POST.get('new_author')
if author_name:
author, created = Author.objects.get_or_create(name=author_name)
else:
author_name = request.POST.get('author')
author = Author.objects.get(name=author_name)
try:
book = Book.objects.get(title=data['title'])
except:
book = Book.objects.create(title=data['title'], author=author)
book.user.add(user)
book.save()
return redirect('/books')
</code></pre>