繁体   English   中英

“函数”对象没有属性“as_view”

[英]'function' object has no attribute 'as_view'

我正在尝试使用基于类的视图,并得到一个奇怪的错误。 我使用视图的方式似乎是正常的方式:

成分/模型.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]

成分/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']

成分/ 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应该是一个类。 所以你的 views.py 替换:

def IngredientCreateView(CreateView):

和:

class IngredientCreateView(CreateView):

就我而言,问题是我试图在基于类的视图上使用 @decorator ,就好像它是基于函数的视图一样,而不是正确地 @decorating 类

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

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

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

IngredientCreateView是一个函数,而不是一个类。

以下行

def IngredientCreateView(CreateView):

应该替换为

class IngredientCreateView(CreateView):

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

File name /api/A.py

class A:
//some methods

在你的主班

//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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM