AttributeError:'BookForm'对象没有属性'get'

时间:2018-04-21 14:56:45

标签: python django

错误:AttributeError:'BookForm'对象没有属性'get'。 我无法调试问题。请提前帮助。谢谢

forms.py

from django import forms
from .models import Book

class BookForm(forms.Form):
class Meta:
    model = Book
    fields = ['title', 'sub_title', 'author', 'image', 'price', 'description', 'ISBN', 'number_of_pages','dimensions', 'interior_pages','binding','availability','genre']

urls.py

from django.urls import path
from . import views
urlpatterns = [
    path('',views.BookForm, name = 'bookform' ),
]

views.py

从django.shortcuts导入渲染,重定向 来自.forms import BookForm

def bookview(request):
    if request.method == 'POST':
        form = BookForm(request.post)
        if form.is_valid():
            model_instance = form.save()
            model_instance.save()
            return redirect('/')
    else:
        form = BookForm()
        return render(request,'book.html',{'myform':form})

模板

<html>
<head>
<title>edit</title>
</head>
<body>

<form method="post" >
{% csrf_token %}
{{form.as_p}}

<input type="submit" value="ok">
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:3)

在网址格式中,您需要将视图与网址路径相关联。但是您在此处使用表单类,将urls.py更改为:

urlpatterns = [
    path('', views.bookview, name='bookform'),
]

另外,要使用自动生成的字段,您需要使用ModelForm作为表单的基类:

class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ['title', 'sub_title', 'author', 'image', 'price', 'description', 'ISBN', 'number_of_pages','dimensions', 'interior_pages','binding','availability','genre']

<强> UPD

您在视图的上下文中有myform个变量,因此您需要在模板而不是form中使用它:

{{myform.as_p}}