python Django表单没有注册用户,即使所有字段都有效

3lxsmp7m  于 2023-04-04  发布在  Python
关注(0)|答案(1)|浏览(133)

在这个应用程序中,我向用户提供了一个注册表单,用户可以在其中输入用户名,密码,确认密码(这个确认不是表单的一部分,而是我在www.example.com中进行的检查,以确保密码匹配views.py),以及他们的电子邮件。出于某种原因,每当我尝试用错误的确认密码注册时,我总是在我的else块中收到错误“出错......请重试!”而不是“密码必须匹配“。我很卡住,不确定出了什么问题,因为在这个功能完全运行之前,我开始为我的应用程序开发其他功能。

查看次数.py

def register(request):
    if request.method == "POST":
        form = UserRegistrationForm(request.POST)
        if form.is_valid():

            username = form.cleaned_data['username']
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            confirmation = request.POST['confirmation']

            # Ensure password matches confirmation
            if password != confirmation:
                messages.error(request, 'Passwords must match.')
                return render(request, "network/register.html", {
                    "register_form": form
                })

            # Attempt to create new user
            try:
                user = User.objects.create_user(username=username, email=email, password=password)
                user.save()
            except IntegrityError:
                messages.error(request, 'Username already taken.')
                return render(request, "network/register.html", {
                    "register_form": form
                })
            login(request, user)
            return HttpResponseRedirect(reverse("index"))
        else:
            # Always returns this whenever submitted
            messages.error(request, 'Something went wrong... Please try again!')
            return render(request, "network/register.html", {
                "register_form": form
            })
    else:
        return render(request, "network/register.html", {
            "register_form": UserRegistrationForm()
        })

表单.py

class UserRegistrationForm(ModelForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password']

        widgets = {
            'username': TextInput(
                attrs={'class': 'input form-control', "placeholder": "Username", 'autocomplete': 'off'}),
            'password': TextInput(
                attrs={'class': 'input form-control', "type": 'password', "placeholder": "Password", 'autocomplete': 'off'}),
            'email': TextInput(
                attrs={"class": "input form-control", "type": 'email', "placeholder": "johndoe@gmail.com", 'autocomplete': 'off'}),
        }

型号.py

class User(AbstractUser, models.Model):
    pass

注册表.html

<!--Form section-->
    <div class="sign-up-section">
        <h2 class="title text-center">Sign Up</h2>
        <div class="sign-up-card">

            <form action= "{% url 'register' %}" method="POST" enctype='multipart/form-data' class='form'>

                {% csrf_token %}
                
                <div class="input-group">
                    <img class="form-icon" src={% static "icons/profile-user.svg" %}>
                    {{register_form.username}}
                </div>
                <div class="input-group">
                    <img class="form-icon" src={% static "icons/key.svg" %}>
                    {{register_form.password}}
                </div>
                <!-- The confirmation will not be part of the Model form, rather just something else to input and compare -->
                <div class="input-group">
                    <img class="form-icon" src={% static "icons/key.svg" %}>
                    <input type="password" name="confirmation" class="form-control" placeholder="Confirm Password">
                </div>
                <div class="input-group">
                    <img class="form-icon" src={% static "icons/envelope.png" %}>
                    {{register_form.email}}
                </div>
                <div class="input-group">
                    <input class="btn btn-primary create-button" type="submit" value="Create Account">
                </div>

            </form>
        </div>
    </div>

没有与此问题相关的追溯错误,只是逻辑不允许我注册用户/当确认与原始密码不匹配时抛出正确的错误。

bvuwiixz

bvuwiixz1#

你没有正确的方法,你的一个字段在你的表单中,而另一个没有。最后你有一个被清理了,而另一个没有。你也在你的视图中检查你的表单。
让我们稍微澄清一下:
forms.py

class UserRegistrationForm(ModelForm):
    confirmation = forms.CharField()
    
    class Meta:
        model = User
        fields = ['username', 'email', 'password', 'confirmation']
        widgets = {
            'username': TextInput(
                attrs={'class': 'input form-control', "placeholder": "Username", 'autocomplete': 'off'}),
            'password': PasswordInput(
                attrs={'class': 'input form-control', "type": 'password', "placeholder": "Password", 'autocomplete': 'off'}),
            'confirmation': PasswordInput(
                attrs={'class': 'input form-control', "type": 'password', "placeholder": "Confirm your password", 'autocomplete': 'off'}),
            'email': TextInput(
                attrs={"class": "input form-control", "type": 'email', "placeholder": "johndoe@gmail.com", 'autocomplete': 'off'}),
        }

    # let's validate your form in a form validation method
    def clean(self):
        cleaned_data = super().clean()
        if cleaned_data['password'] != cleaned_data['confirmation']:
                self.add_error('password', "Your password is different from the confirmation!")

现在你的密码验证是在表单中完成的,这意味着如果密码不相同,调用.is_valid()将返回False,并在表单中加载错误消息。现在你可以让你的视图更简洁:
views.py:

def register(request):
    if request.method == "POST":
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
           user = form.save() # this will put an error in case the username is taken and will be brought back in the form to display on your template
           login(request, user) #This is a VERY bad idea to login on register
            return HttpResponseRedirect(reverse("index"))
        else:
            # Always returns this whenever submitted
            messages.error(request, 'Something went wrong... Check the form for more informations')
            return render(request, "network/register.html", {
                "register_form": form
            })
    else:
        return render(request, "network/register.html", {
            "register_form": UserRegistrationForm()
        })

最后,你应该在你的模板中显示错误,以知道到底是什么问题,Django表单保留表单和模型验证返回的错误消息。你可以让它漂亮,但如果你想看到它们用于调试,你可以在你的模板中添加:

{% if form.errors %}
<div id="form-error">
    <p>errors list:</p>
    <ul>
    {% for field in register_form %}
    <li>{{ field.errors|striptags }}</li>
    {% endfor %}
    </ul>
</div>
{% endif %}

这将显示哪个验证失败

相关问题