Fun Creator
Fun Creator

Reputation: 45

How can I fix Exception Value: 'module' object is not callable

My problem in this line:

args.update(csrf(request))

My function in vews.py:

def Login(request):
    args = {}
    args.update(csrf(request))
    if request.POST:
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = authenticate(username = username, password = password)
        print(user, username, password)
        if user is not None:
            auth.login(request, user)
            return redirect('/')
        else:
            args['login_error'] = "Пользователь не найден"
            return render(request, 'HiPage/Login.html', args)

    else:
        return render(request, 'HiPage/Login.html', args)

What is module here and why is it uncallable? (I made imports of csrf)

  File "C:\Users\Dmitry\Desktop\Shop-master\HiPage\views.py", line 51, in Login
    args.update(csrf(request))
TypeError: 'module' object is not callable

Upvotes: 1

Views: 259

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477749

Based on the comments, you have a wrong understanding on how CSRF is implemented in Django.

it's necessary to provide the template with csrf. I tried do it without this string, but I got csrf error.

That is correct. But you do not need to add this to the context variables. If you use 'django.middleware.csrf.CsrfViewMiddleware' as middleware , then the check of the CSRF token happens automatically.

What you need to do, is define the {% csrf_token %} template tag [Django-doc] in your template, like:

<form method="post" action="...">
    {% csrf_token %}
    <!-- ... -->
</form>

In the view, there is no need to generate, or to check the CSRF token.

In your view, you should check request.method == 'POST' instead of if request.POST, since a POST request can be made without data.

According to PEP-8 it is also advisable to write functions in lowercase with underscores.

Finally, if you make a redirect(..), it is better to use the name of the view. If you later change the path of that view, then the URL to which you redirect will change as well.

def login(request):
    args = {}
    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = authenticate(username=username, password=password)
        print(user, username, password)
        if user is not None:
            auth.login(request, user)
            return redirect('name-of-view')
        else:
            args['login_error'] = "Пользователь не найден"
            return render(request, 'HiPage/Login.html', args)

    else:
        return render(request, 'HiPage/Login.html', args)

Upvotes: 1

Related Questions