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

如何解决Django“ AttributeError:'function'对象没有属性'as_view'”

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

这是错误;

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 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('',]

和我的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,**kwargs):
        return super(UserUpdateView,self).dispatch(self,**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'),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的方式,但是我没有帮助它产生相同的错误

解决方法

您不能在基于类的视图上使用@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]的攻击。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?