Django AttributeError: 'function' object has no attribute 'as_view' in urls.py
urls.py file
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'),
]
views.py file
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 file
from django.forms import ModelForm
from .models import *
class QuestionForm(ModelForm):
class Meta:
model = Question
fields = ('author', 'title', 'body')
some more details, some more details, some more details.
It means QuestionView
, Ask
, or QuestionCurrent
are not class-based views. If these are functions, then you can't use .as_view()
[Django-doc] .
The .as_view()
function is used to turn the class of class-based view into a function that will handle the requests. In case the QuestionView
, Ask
and/or QuestionCurrent
views are thus functions, you should drop the .as_view()
of the corresponding views:
urlpatterns = [
path('', views.),
path('ask/', views.),
path('<hex:pk>/', views., name='question_current'),
]
As you can see in the views, the QuestionView
and the Ask
are functions :
QuestionView(request):
''' List of Questions '''
questions = Question.objects.all()
return render(request, 'f/index.html', {'question_list': questions})
QuestionCurrent(request, pk):
''' Current Question '''
question = Question.objects.get(id=pk)
return render(request, 'f/current.html', {'question': question})
Only Ask
is a class-based view.
Furthermore such functions are usually written in snake_case
, not in PerlCase
.
You didn't import Ask class view in the url.py!
I think you forgot to do this: From.views import Ask
also QuestionView was created using function View. You can't call it using as_view().
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.