繁体   English   中英

Django AttributeError: 'function' object has no attribute 'as_view' in urls.py

[英]Django AttributeError: 'function' object has no attribute 'as_view' in urls.py

Django AttributeError: 'function' object has no attribute 'as_view' in urls.py

urls.py 文件

from django.urls import path, register_converter
from . import views, converter

register_converter(converter.HexConverter, 'hex')

urlpatterns = [
    path('', views.QuestionView.as_view()),
    path('ask/', views.Ask.as_view()),
    path('<hex:pk>/', views.QuestionCurrent.as_view(), name='question_current'),
]

视图.py 文件

from django.views.generic.edit import CreateView
from django.shortcuts import render
from .forms import QuestionForm
from .models import *

def QuestionView(request):
    ''' List of Questions '''
    questions = Question.objects.all()
    return render(request, 'f/index.html', {'question_list': questions})

def QuestionCurrent(request, pk):
    ''' Current Question '''
    question = Question.objects.get(id=pk)
    return render(request, 'f/current.html', {'question': question})

class Ask(CreateView):
    template_name = 'f/ask.html'
    form_class = QuestionForm
    success_url = '/f/ask/'

    def get_context_data(self, **kwargs):
        content = super().get_context_data(**kwargs)
        return content

forms.py 文件

from django.forms import ModelForm
from .models import *

class QuestionForm(ModelForm):
    class Meta:
        model = Question
        fields = ('author', 'title', 'body')

更多细节,更多细节,更多细节。

这意味着QuestionViewAskQuestionCurrent不是基于类的视图。 如果这些是函数,那么您不能使用.as_view() [Django-doc]

.as_view() function 用于将基于类的视图的 class 转换为将处理请求的 function。 如果QuestionViewAsk和/或QuestionCurrent视图因此是函数,则应删除相应视图的.as_view()

urlpatterns = [
    path('', views.QuestionView),
    path('ask/', views.Ask.as_view()),
    path('<hex:pk>/', views.QuestionCurrent, name='question_current'),
]

正如您在视图中看到的, QuestionViewAsk函数

def QuestionView(request):
    ''' List of Questions '''
    questions = Question.objects.all()
    return render(request, 'f/index.html', {'question_list': questions})

def QuestionCurrent(request, pk):
    ''' Current Question '''
    question = Question.objects.get(id=pk)
    return render(request, 'f/current.html', {'question': question})

Only Ask是一个基于类的视图。

此外,这些函数通常是用snake_case编写的,而不是PerlCase

您没有在 url.py 中导入 Ask class 视图!

我想你忘了这样做:From.views import Ask

QuestionView 也是使用 function 视图创建的。 您不能使用 as_view() 调用它。

暂无
暂无

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

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