Django:更改模型表单中的字段类型,然后将其应用于模型类

时间:2010-11-29 15:35:10

标签: python django django-models django-forms

我有一个班级Book

from django.db import models
from users.models import User

class Book(models.Model):
    title = models.CharField(max_length=150)
    authors = models.ManyToManyField("Author")

链接到Author类:

class Author(models.Model):
    name = models.CharField(max_length=150)
    birthday = models.DateField()

我有一个名为BookForm

的Book类的表单
from django import forms
from django.forms import CharField
from books.models import Book
class BookForm(forms.ModelForm):
    authors = CharField()
    class Meta:
        model = Book
        fields = ["title","authors"]

我想用BookForm创建一个很简单的书籍,但不是像默认情况下那样从列表中选择作者(因为它是一个ManyToManyField),我希望用户能够输入文本,每个作者姓名的逗号分隔字符串。我的观点是这样设置的:

def create_book(request):
    if request.user is None:
        return redirect("/users/login/")
    if request.method == "POST":
        form = BookForm(request.POST)
        if form.is_valid():
            nbook = form.save(commit=False)
            authorlist = form.authors.split(",")
            nbook.owner = request.user
            nbook.save()
            for auth in authorlist:
                nbook.authors.create(name=auth)
            return redirect("/books/")
    else:
        form = BookForm()
    return render_to_response("books/create.html", {
        "form": form,
    }, context_instance=RequestContext(request))

但这不起作用。我收到错误'BookForm' object has no attribute 'authors'。我不确定这里是否存在根本问题,或者它的语法是否正确,但有人可以帮忙吗?我对Python和Django都是全新的:[

谢谢!

1 个答案:

答案 0 :(得分:1)

要停止django自动创建<select>表单条目,请从字段列表中删除'authors'

class BookForm(forms.ModelForm):
    authors = CharField()
    class Meta:
        model = Book
        fields = ["title"]

Django覆盖了您使用自动创建的作者创建的作者条目。

至于第二个错误,从绑定表单获取数据的正确方法不是form.authors,而是来自form.cleaned_data['authors']

P.S。你从这开始:

if request.user is None:
    return redirect("/users/login/")

为此,您应该使用login_required装饰器。