Django“ AttributeError:'function'对象没有属性'as_view'”

时间:2020-09-26 17:22:05

标签: django django-views django-urls django-class-based-views

我正在尝试使用基于类的视图制作索引页,该类视图将具有菜单栏,并通过该菜单栏将重定向到新页面,并将表单作为发布请求。但是无论我做什么,我总是会遇到相同的错误。

这是错误;

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\berat.berkol\anaconda3\lib\threading.py", line 926, in _bootstrap_inner
    self.run()
  File "C:\Users\berat.berkol\anaconda3\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run
    self.check(display_num_errors=True)
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\management\base.py", line 396, in check
    databases=databases,
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
    return check_method()
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\urls\resolvers.py", line 408, in check
    for pattern in self.url_patterns:
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module
    return import_module(self.urlconf_name)
  File "C:\Users\berat.berkol\anaconda3\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\berat.berkol\SystemConsole\SystemConsole\urls.py", line 25, in <module>
    path('', UserUpdateView.as_view(), name='home'),
AttributeError: 'function' object has no attribute 'as_view'

还有我项目的urls.py;

from django.contrib import admin
from django.urls import path
from django.conf.urls import include
from userupdate.views import UserUpdateView

app_name='userupdate'
urlpatterns = [
    path('admin/', admin.site.urls),
    path('login/',include('django.contrib.auth.urls')),
    path('', UserUpdateView.as_view(), name='home'),
]

和我的views.py;

from django.shortcuts import render
from datetime import timedelta
from django.utils import timezone
from django.views.generic import TemplateView
from django.views.decorators.csrf import csrf_protect
from django.utils.decorators import method_decorator
from django.urls import reverse
import requests
from userupdate.forms import UserPassForm
from userupdate.forms import LoginForm
from django.views.generic import View
from django.contrib.auth.views import LoginView
from django.contrib.auth.mixins import LoginRequiredMixin

@csrf_protect
class UserUpdateView(LoginRequiredMixin,View):
    emplate_name='home.html'
    def get(self, request, *args, **kwargs):
        return render(request,'home.html')
    #@method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(UserUpdateView, self).dispatch(self, request, *args, **kwargs)


@csrf_protect
class LoginUser(LoginView):
    template_name = 'home.html'  # your template
    from_class = LoginForm()  # your form

    def get_success_url(self):
        '''Here the part where you can implement your login logic'''
        now = timezone.now()
        # Get current day date object
        # like: 12/02/2019 00:00:00
        today = now.replace(minute=0).replace(second=0).replace(microsecond=0)
        # Get the client from the user object
        client = self.request.user.cli
        # Get all the user today's logins and count them
        client_logins = models.ClientLogins.objects.filter(
            client=client,
            date__gte=today,
            date__lte=today + timedelta(days=1)
        ).count()
        if client_logins < 1:  # Or: if not client_logins:
            # create a login tracker record
            models.ClientLogins.objects.create(
                client=client,
                date=now  # Store the date where the user logged in the website
            )
            return reverse_lazy('home')
        # Or redirect to: settings.LOGIN_REDIRECT_URL
        request.session.get_expire_at_browser_close()
        return super().get_success_url()

@csrf_protect
class passResetView(View):

    def get(self,request):


        form=UserUpdateForm()

        return render('basarili')

    def post(self,request):
        passResetuser=self.model.objects.get(pk=2)

        form=UserUpdateForm(request.POST,instance=passResetuser)

        if form.is_valid():
            username=form.cleaned_data('username')
            password=form.cleaned_data('password')
            number=form.cleaned_data('number')
            message=form.cleaned_data('message')

        context={'form':form}
        return render(request,'home.html',context)

我不知道是否需要,但这是我的应用程序的urls.py;

from django.urls import path, re_path
from django.contrib.auth.views import LoginView
from userupdate.views import HomeView
from django.contrib.auth import views as auth_views


app_name='userupdate'
urlpatterns = [
    path('', views.UserUpdateView.as_view(template_name='home.html'), name='home'),
    path('login/', 
       LoginView.as_view(
           template_name='login.html'), 
           name="login"),
    #path('passResetView',views.passResetView.as_view(template_name="home.html"),name='passResetView'),
    path('passreset/', 
       passResetView.as_view(
           template_name='passreset.html'), 
           name="PasswordReset"),

]

我尚未配置表单页面,因此暂时将其忽略。

我将使用FormView构建它们。

通过我也尝试了TemplateView的方式,但是我没有帮助它产生相同的错误。

1 个答案:

答案 0 :(得分:2)

您不能在基于类的视图上使用@csrf_protect,或者至少不能直接使用。该装饰器将返回一个函数,并且该函数当然没有.as_view()方法。

您可以使用@method_decorator [Django-doc],它将装饰类:

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect

@method_decorator(csrf_exempt, name='dispatch')
class UserUpdateView(LoginRequiredMixin,View):
    template_name = 'home.html'

    # …

话虽这么说,豁免CSRF通常不是一个好主意,因为这会使您的视图容易受Cross-Site Request Forgery [wiki]的攻击。<​​/ p>