1

I am trying to make an index page with class based views that will have menu bar and with that menu bar it will redirect to new pages and takes forms as post requests. But whatever i do i always get the same error.

Here is the error ;

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'

And my project's 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'),
]

and my 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)

I don't know if it's required but here is my app's 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"),

]

I haven't configured the form pages yet so ignore them for now.

I will build them with the FormView.

By the way I tried the TemplateView also but i didn't help its makes the same error.

3
  • You can't use @csrf_protect on a class-based view, since that will return a function. Commented Sep 26, 2020 at 17:25
  • Note that you also made a typo with emplate_name: it should be template_name. Commented Sep 26, 2020 at 17:30
  • thanks, there is no typo actually i deleted accidently when i copied here. Commented Sep 26, 2020 at 21:11

1 Answer 1

4

You can't use @csrf_protect on a class-based view, or at least not directly. This decorator will return a function, and that function of course has no .as_view() method.

You can work with the @method_decorator [Django-doc], which will decorate the class:

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'

    # …

That being said, it is often not a good idea to make a CSRF exempt, since that makes your view vulnerable to Cross-Site Request Forgery [wiki].

Sign up to request clarification or add additional context in comments.

2 Comments

wrapping the post(...) method with @csrf_protect will also work, won't it?
@ArakkalAbu: no, since the .as_view() function needs to have an attribute .csrf_exempt = True, and the .as_view takes this from the dispatch method: github.com/django/django/blob/master/django/views/generic/… If you decorate the post method, then the result .as_view(), will not "copy" that attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.