Python “函数”对象没有属性“as_view”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34217400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'function' object has no attribute 'as_view'
提问by codyc4321
I am trying to use class based views, and get a strange error. The way I'm using the view seems to be the normal way:
我正在尝试使用基于类的视图,并得到一个奇怪的错误。我使用视图的方式似乎是正常的方式:
ingredients/models.py:
成分/模型.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:
成分/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:
成分/ 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'),
)
I get
我得到
AttributeError at /ingredients/new_ingredient
'function' object has no attribute 'as_view'
I am on django 1.8.5. Why won't this view work? Thank you
我在 Django 1.8.5 上。为什么这个视图不起作用?谢谢
采纳答案by Anush Devendra
IngredientCreateView
should be a class.
So your views.py replace:
IngredientCreateView
应该是一个类。所以你的 views.py 替换:
def IngredientCreateView(CreateView):
with:
和:
class IngredientCreateView(CreateView):
回答by falsetru
IngredientCreateView
is a function, not a class.
IngredientCreateView
是一个函数,而不是一个类。
The following line
以下行
def IngredientCreateView(CreateView):
should be replace with
应该替换为
class IngredientCreateView(CreateView):
回答by krubo
In my case, the problem was that I tried to use a @decorator on the class-based view as if it was a function-based view, instead of @decorating the class correctly.
就我而言,问题是我试图在基于类的视图上使用 @decorator ,就好像它是基于函数的视图一样,而不是正确地 @decorating 类。
回答by Shirish Singh
In addition to what is already said here, Check the file name and class name if it is same then you might have to import the class properly.
除了这里已经说过的内容之外,检查文件名和类名如果相同,那么您可能需要正确导入类。
File name /api/A.py
class A:
//some methods
In your main class
在你的主班
//App main class
from api.A import A