简体   繁体   中英

AttributeError: 'function' object has no attribute 'as_view'. What's wrong?

Good afternoon, I am trying to solve this problem, but all my attempts to solve it myself have only resulted in changing def to class. and this does not help? Can you tell me what the problem is?

views.py

from django.core.mail import send_mail, BadHeaderError
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from .models import Form

def FormListView(request):
    if request.method == 'GET':
        form = FormListView()
    else:
        form = FormListView(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            surname = form.cleaned_data['surname']
            email = form.cleaned_data['email']
            try:
                send_mail(name, surname, email, ['kirill_popov_000@mail.ru'])
            except BadHeaderError:
                return HttpResponse('Invalid')
            return redirect('success')
    return render(request, "index.html", {'form': form})

def Success(request):
    return HttpResponse('Success!')

urls.py

from django.urls import path
from .views import FormListView

urlpatterns = [
    path('', FormListView.as_view(), name = 'home'),
    path('success/', Success.as_view(), name = 'success')
]

errat:

  File "/home/user/Portfolio/web_project/web_page/urls.py", line 5, in <module>
    path('', FormListView.as_view(), name = 'home'),
AttributeError: 'function' object has no attribute 'as_view'

You are using a function instead of a class-based View. Have a look at thisreference .

function-based

If you are using a function you can basically write (maybe change to lower case of the the function for convention).

path('', FormListView(), name = 'home'),

class-based

if you have for example a class-based view like:

from django.views.generic import TemplateView

class AboutView(TemplateView):
#...

Then you can use as_view() like this:

path('about/', AboutView.as_view()),

They are function rather than class based views. In class based views you type.as_view() after the name, but in function based views you just need to type FormListView without brackets.

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.

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