Django 形式。 POST 请求

问题描述 投票:0回答:2

当用户无法登录时(例如因为他输入了错误的密码)页面重新加载并显示密码不正确,然后,当用户再次重新加载页面时,将生成具有相同填写字段和相同错误的相同表单页。问题是,不知何故在重新加载方法之后仍然是 POST。为什么?我希望表格在我重新加载页面时自行清除。

我是 Django 的新手,所以,我希望有人能帮助我!

views.py

from django.forms import ValidationError
from django.shortcuts import render, redirect
from .forms import LogInForm, SignUpForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth.hashers import make_password
from django.contrib.auth import authenticate, logout, login as auth_login
from django.contrib import messages
from django.http import HttpResponseRedirect, HttpResponse
# Create your views here.


def login(request):
    logInForm = LogInForm()
    if request.method == 'POST':    
        form = LogInForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            user = authenticate(
                username=cd['username'], password=cd['password'])
            if user is not None:
                auth_login(request, user)
                return redirect("home")
            else:
                messages.error(request, "Invalid login or password")
                return render(request, 'logIn.html', {"form": form})
        else:
            return HttpResponse("afs")
    else:
        return render(request, 'logIn.html', {"form": logInForm})


def logout_view(request):
    logout(request)
    return redirect('login')


@login_required
def profile(request):
    return render(request, 'profile.html')


@login_required
def toDoList(request):
    current_user = request.user
    username = current_user.username
    return render(request, 'toDoList.html', {'username': username})


def signUp(request):
    signUpForm = SignUpForm()
    if (request.method == 'POST'):
        form = SignUpForm(request.POST)
        if (form.is_valid()):
            user = form.save(commit=False)
            user.password = make_password('password')
            user.save()
            auth_login(request, user)
            username = user.username
            return render(request, "toDoList.html", {'username': username})
        else:
            return render(request, 'signUp.html', {"form": form})
    else:
        return render(request, 'signUp.html', {"form": signUpForm})

forms.py

from django.forms import ModelForm, ValidationError
from django import forms
from .models import User
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages

class LogInForm(forms.Form):
    username = forms.CharField(widget=forms.TextInput(
        attrs={'placeholder': 'Username', 'class': 'form-input'}),required=True)
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={'placeholder': 'Password', 'class': 'form-input'}),required=True)
    def check_pass(self):
        cleaned_data = super(SignUpForm, self).clean()
        password = self.cleaned_data.get("password")
        if (password == ''):
            messages.error("Invalid data")
        return cleaned_data


class SignUpForm(ModelForm):
    password = forms.CharField(label='Password', widget=forms.PasswordInput(
        attrs={"placeholder": "Password"}))
    password2 = forms.CharField(
        label='Confirm password', widget=forms.PasswordInput(attrs={"placeholder": "Confirm password"}))

    class Meta:
        model = User
        fields = ('username', 'email', 'phoneNumber','password')
        widgets = {
            "username": forms.TextInput(
                attrs={
                    "placeholder": "Username"
                }
            ),
            "email": forms.TextInput(
                attrs={
                    "placeholder": "Email"
                }
            ),
            "phoneNumber": forms.TextInput(
                attrs={
                    "placeholder": "Phone number (with a country code) ",
                    "type": "tel",
                    "minlength": 12,
                    "maxlength": 12,
                },
            ),
        }

    def clean(self):
        cleaned_data = super(SignUpForm, self).clean()
        password = self.cleaned_data.get("password")
        confirm_password = self.cleaned_data.get("password2")
        if password and confirm_password:
            if password != confirm_password:
                self.add_error(None, "Passwords don't match")
        return cleaned_data

    def checkIfExist(self):
        cleaned_data = super(SignUpForm, self).clean()
        username = self.cleaned_data.get("username")
        email = self.cleaned_data.get("email")
        phoneNumber = self.cleaned_data.get("phoneNumber")
        if User.objects.filter(email.exists()):
            self.add_error('email', "That email already exists")
        if User.objects.filter(username.exists()):
            self.add_error('username', "That username already exists")
        if User.objects.filter(phoneNumber.exists()):
            self.add_error('phoneNumber', "That phone number already exists")
        return cleaned_data

logIn.html

<!DOCTYPE html>
{% load static %}

<html>
    <head>
        <link rel="stylesheet" href="{% static "css/login.css" %}" />
        <link rel="stylesheet"
            href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <link rel="icon" href="data:;base64,=">
        <title>To do list</title>
        <style>
            .container{
               background-image: url('{% static "images/background.jpg" %}');
               background-size:100% 100%;
            }
        </style>
    </head>

    <body>
        <div class="container">
            <form action="" class="form" method="post">
                {% csrf_token %}
                <h1 class="title">Log in</h1>
                {{form.as_table}}
                {% if messages %}
                    {% for message in messages %}
                        {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}
                            <div class="message">
                                <span class="message-error">{{ message }}</span>
                            </div>
                        {% endif %}
                    {% endfor %}
                {% endif %}
                <label class="label-checkbox" for="rememberMe">
                    <input type="checkbox" name="rememberMe" class="form-check">
                    Remember me
                </label>
                <div class="wrapper">
                    <button type="submit" class="form-butn">Log in</button>
                    <a class="form-signUp" href="/signUp">Sign Up</a>
                </div>
                {% if form.non_field_errors %}
                <div class="non-field-errors">
                    {% for err in form.non_field_errors %}
                    <span class="form-error">{{ err }}</span>
                    {% endfor %}
                </div>
                {% endif %}
                <div class="div-social">
                    <span>Войти с помощью</span>
                </div>
                <ul class="list">
                    <li class="social">
                        <a href="" class="social-btn">
                            <img class="login" src="{% static "images/google.svg" %}" alt="google">
                        </a>
                    </li>
                    <li class="social">
                        <a href="" class="social-btn">
                            <img class="login" src="{% static "images/tg.svg" %}" alt="telegram">
                        </a>
                    </li>
                    <li class="social">
                        <a href="" class="social-btn">
                            <img class="login" src="{% static "images/vk.svg" %}" alt="vk">
                        </a>
                    </li>
                    <li class="social">
                        <a href="" class="social-btn">
                            <img class="login" src="{% static "images/yandex.png" %}" alt="yandex">
                        </a>
                    </li>
                </ul>
            </form>
        </div>
    </body>
</html>

在登录函数程序(或其他任何东西)中重新加载带有完整表单的页面后,通过第一个条件(request.method =='POST'),然后通过下一个条件(form.is_valid()),返回True,然后它转到“如果用户不是无”,转到其他并呈现带有错误的完整表单的页面。

python django post
2个回答
0
投票

这个我漏了,也改一下:

else:
    messages.error(request, "Invalid login or password")
    return render(request, 'logIn.html', {"form": form})####

至:

else:
    messages.error(request, "Invalid login or password")
    return redirect("login")####

试试这个。如果它仍然不起作用,请告诉我您遇到的错误。

password1 = forms.CharField(label = False, required = True,error_messages={
        'required': 'Password is required.',
        },
    widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'})
    )

    password2 = forms.CharField(label = False, required = True,error_messages={
        'required': 'Password is required.',
        },
    widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Confirm Password'})
    )

    error_messages = {
        'password_mismatch': 'Passwords must match.',
    }

0
投票

分配你的表格:

def login(request):
    logInForm = LogInForm()
    if request.method == 'POST':    
        form = LogInForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            user = authenticate(
                username=cd['username'], password=cd['password'])
            if user is not None:
                auth_login(request, user)
                return redirect("home")
            else:
                messages.error(request, "Invalid login or password")
                return render(request, 'logIn.html', {"form": form})
        else:
            form = LogInForm()######
    else:
        return render(request, 'logIn.html', {"form": form})######
© www.soinside.com 2019 - 2024. All rights reserved.