Django身份验证表单未正常工作。

huangapple go评论63阅读模式
英文:

Django Authentication Form not working properly

问题

以下是翻译好的部分:

我正在尝试创建一个非常基本的登录系统只是为了了解Django的身份验证系统没有什么花哨的东西)。

问题是当我使用以下代码时即不验证身份验证表单提交时),一切都**完美运行**

*views.py*文件

```python
from django.shortcuts import render, redirect
from django.http import request
from django.contrib.auth.decorators import login_required
from .forms import UserRegistrationForm
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import AuthenticationForm

@login_required(login_url="accounts/login")
def home(request):
    return render(request, "main/home.html")

def register_user(request):
    if request.method == "POST":
        reg_form = UserRegistrationForm(request.POST)
        if reg_form.is_valid():
            user = reg_form.save()

            messages.success(request, f'You have successfully registered!')
            return redirect("login")
        else:
            messages.error(request, "Some problem occured")
    else:
        reg_form = UserRegistrationForm()
    return render(request, template_name='main/register.html', context={"form":reg_form})
    
def login_view(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        user = authenticate(request, username = username, password = password)

        if user is not None:
            login(request, user)
            messages.success(request, f"You logged in as: {username}")
                    
            return redirect("home")
        else:
            messages.error(request, "Invalid username or password")
            return redirect("login")
    else:
        auth_form = AuthenticationForm()
    return render(request, "registration/login.html", context={"form":auth_form})

def logout_request(request):
    logout(request)
    messages.success(request, f"You have logged out.")
    return redirect("login")

然而,当我插入身份验证表单验证和填充时,用户未经过身份验证,而是返回了None。

出于简化的目的,我只添加了'login_view',因为这是我遇到问题的地方。

def login_view(request):
    if request.method == "POST":
        auth_form = AuthenticationForm(request.POST)
        if auth_form.is_valid():
            username = auth_form.cleaned_data.get("username")
            password = auth_form.cleaned_data.get("password")
            user = authenticate(request, username = username, password = password)

            if user is not None:
                login(request, user)
                messages.success(request, f"You logged in as: {username}")
                    
                return redirect("home")
            else:
                messages.error(request, "Invalid username or password")
                return redirect("login")
        else:
            messages.error(request, f"Some problem encountered.")
            return redirect("login")
    else:
        auth_form = AuthenticationForm()
    return render(request, "registration/login.html", context={"form":auth_form})

注意: 我知道这样的if-else嵌套不被鼓励,不应该使用。但我只是好奇为什么前一种解决方案有效而后一种解决方案无效。

感谢帮助。

英文:

I am trying to create a very basic login system (just to grasp Django's authentication system, nothing fancy).

Thing is, when I use the following code (i.e. don't validate authentication form submission), everything works perfectly.

The views.py file:

from django.shortcuts import render, redirect
from django.http import request
from django.contrib.auth.decorators import login_required
from .forms import UserRegistrationForm
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import AuthenticationForm

@login_required(login_url="accounts/login")
def home(request):
    return render(request, "main/home.html")

def register_user(request):
    if request.method == "POST":
        reg_form = UserRegistrationForm(request.POST)
        if reg_form.is_valid():
            user = reg_form.save()

            messages.success(request, f'You have successfully registered!')
            return redirect("login")
        else:
            messages.error(request, "Some problem occured")
    else:
        reg_form = UserRegistrationForm()
    return render(request, template_name='main/register.html', context={"form":reg_form})
    
def login_view(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        user = authenticate(request, username = username, password = password)

        if user is not None:
            login(request, user)
            messages.success(request, f"You logged in as: {username}")
                    
            return redirect("home")
        else:
            messages.error(request, "Invalid username or password")
            return redirect("login")
    else:
        auth_form = AuthenticationForm()
    return render(request, "registration/login.html", context={"form":auth_form})

def logout_request(request):
    logout(request)
    messages.success(request, f"You have logged out.")
    return redirect("login")

However, when I insert authentication form validation and population, user is not authenticated and None is returned instead.

For the purpose of simplicity I am adding the 'login_view' only as this is where I encounter the problem.

def login_view(request):
    if request.method == "POST":
        auth_form = AuthenticationForm(request.POST)
        if auth_form.is_valid():
            username = auth_form.cleaned_data.get("username")
            password = auth_form.cleaned_data.get("password")
            user = authenticate(request, username = username, password = password)

            if user is not None:
                login(request, user)
                messages.success(request, f"You logged in as: {username}")
                    
                return redirect("home")
            else:
                messages.error(request, "Invalid username or password")
                return redirect("login")
        else:
            messages.error(request, f"Some problem encountered.")
            return redirect("login")
    else:
        auth_form = AuthenticationForm()
    return render(request, "registration/login.html", context={"form":auth_form})

NOTE: I know such an if-else ladder is discouraged and shouldn't be used. But I'm just curious as to why the former solution works and the latter one does not.

Thanks for the help.

答案1

得分: 1

Django AuthenticationForm的第一个参数是一个请求对象。您可以将提交的数据作为data参数提供,例如request.POST

auth_form = AuthenticationForm(None, data=request.POST)

英文:

The Django AuthenticationForm takes a request object as its first argument. You can provide submitted data like request.POST as the data kwarg

auth_form = AuthenticationForm(None, data=request.POST)

huangapple
  • 本文由 发表于 2023年6月25日 22:50:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76550993.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定