'function' 对象没有属性 'as_view'

'function' object has no attribute 'as_view'

我正在尝试使用基于 class 的视图,但出现了一个奇怪的错误。我使用视图的方式似乎是正常方式:

ingredients/models.py:

from django.db import models
from django.utils import timezone


class Ingredient(models.Model):
    name        = models.CharField(max_length=255)
    description = models.TextField()

    def get_prices():
        purchases   = self.purchase_set.all()
        prices      = [purchase.price for purchase in purchases]

ingredients/views.py:

from django.shortcuts           import render, render_to_response, redirect
from django.http                import HttpResponse, HttpResponseRedirect
from django.views.generic.edit  import CreateView
from .models                    import Ingredient, Purchase

def IngredientCreateView(CreateView):
    model = Ingredient
    fields = ['all']

ingredients/urls.py:

from django.conf.urls import patterns, include, url

from ingredients.views import IngredientCreateView

urlpatterns = patterns('',            
    url(r'^new_ingredient$',          IngredientCreateView.as_view(),             name='new-ingredient'),
)

我明白了

AttributeError at /ingredients/new_ingredient
'function' object has no attribute 'as_view'

我正在使用 Django 1.8.5。为什么这个观点不起作用?谢谢

IngredientCreateView 应该是 class。 所以你的 views.py 替换:

def IngredientCreateView(CreateView):

与:

class IngredientCreateView(CreateView):

IngredientCreateView 是函数,不是 class。

下面一行

def IngredientCreateView(CreateView):

应替换为

class IngredientCreateView(CreateView):

在我的例子中,问题是我试图在基于 class 的视图上使用 @decorator,就好像它是基于函数的视图一样,而不是 @decorating the class correctly.

编辑:从链接页面,这里有一种将@login_required应用于基于class的视图的方法:

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

@method_decorator(login_required, name='dispatch')
class ProtectedView(TemplateView):

除了这里已经说过的之外,检查文件名和 class 名称如果相同,那么您可能需要正确导入 class。

File name /api/A.py

class A:
//some methods

在你的主class

//App main class
from api.A import A

我遇到了同样的问题,但这个解决方案对我有用..

views.py 文件中的视图类中,您可以使用视图集而不是 CreateView

            from rest_framework import viewsets
            class YourClassView(viewsets.ModelViewSet):

urls.py文件中你可以使用这个路由模式

          from django.conf.urls import url
          from rest_framework import routers

          router = routers.DefaultRouter()
          router.register('books',YourClassView)

          urlpatterns = [
               path('', include(router.urls)),
               path('admin/', admin.site.urls)
            ]
def Some_def_View(CreateView):

#应替换为

class SomeClassView(CreateView)