[英]'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.