Django在表单中验证数据的问题

yshpjwxd  于 2023-06-25  发布在  Go
关注(0)|答案(2)|浏览(154)

所以我一直在努力通过这个教程,我遇到了一个问题,我不能弄清楚。我希望有人能给我指路。我正在处理一个新的用户注册表单,但无法获得要用form.is_valid()验证的数据。在www.example.com中views.py,if form.is_valid()应该验证输入到表单中的数据,但无论如何它都会返回“Invalid”。我对Python和Django相对较新,因此任何帮助都将不胜感激。
views.py:

# main/views.py

from django.http import HttpResponse
from django.contrib.auth import login
from django.shortcuts import redirect, render
from django.urls import reverse
from main.forms import CustomUserCreationForm

# Create your views here.

def main(request):
    return render(request, 'main.html', {})

def dashboard(request):
    return render(request, 'users/dashboard.html')

def admin(request):
    return render(request, 'admin')

def login(request):
    return render(request, 'registration/login.html')

def register(request):
    if request.method == 'GET':
        return render(
            request, 'users/register.html',
            {'form': CustomUserCreationForm}
        )
    elif request.method == 'POST':
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return HttpResponse('<h1>Validated!</h1>')
#            return render(redirect(reverse('dashboard')))
        else:
            return HttpResponse('<h1>Invalid</h1>')

forms.py:

# main/forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        fields = UserCreationForm.Meta.fields + ('email',)

register.html:

<!-- main/templates/users/register.html -->

{% extends 'main.html' %}

{% block content %}
<h2>Register</h2>

<form method="post">
    {% csrf_token %}
    <table>
        {{ form.as_table }}
    </table>
    <input type="submit" value="Register">
</form>

<a href="{% url 'login' %}">Back to login</a>
{% endblock %}

主页urls.py:

# homesite/urls.py

from django.contrib import admin
from main import views
from django.conf.urls import include
from django.urls import path
from main.views import dashboard, register

app_name = 'main'

urlpatterns = [
    path('', views.main, name='main'),
    path('admin/', admin.site.urls),
    path('dashboard/', dashboard, name='dashboard'),
    path('accounts/', include('django.contrib.auth.urls')),
    path('register/', register, name='register'),
]

错误消息:

ValueError at /register/

The view main.views.register didn't return an HttpResponse object. It returned None instead.

Request Method:     POST
Request URL:    https://example.com/register/
Django Version:     4.2.1
Exception Type:     ValueError
Exception Value:    

The view main.views.register didn't return an HttpResponse object. It returned None instead.

Exception Location:     /home/lennys/dev/example.com/env/lib/python3.10/site-packages/django/core/handlers/base.py, line 332, in check_response
Raised during:  main.views.register
Python Executable:  /usr/bin/python3
Python Version:     3.10.6
Python Path:    

['/home/lennys/dev/example.com',
 '/home/lennys/dev/example.com/env/lib/python3.10/site-packages',
 '/usr/lib/python310.zip',
 '/usr/lib/python3.10',
 '/usr/lib/python3.10/lib-dynload',
 '/usr/local/lib/python3.10/dist-packages',
 '/usr/lib/python3/dist-packages']

Server time:    Fri, 16 Jun 2023 08:58:17 -0700

traceback:

Environment:

Request Method: POST
Request URL: https://example.com/register/

Django Version: 4.2.1
Python Version: 3.10.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'main']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']


Traceback (most recent call last):
  File "/home/lennys/dev/example.com/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/lennys/dev/example.com/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 204, in _get_response
    self.check_response(response, callback)
  File "/home/lennys/dev/example.com/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 332, in check_response
    raise ValueError(

Exception Type: ValueError at /register/
Exception Value: The view main.views.register didn't return an HttpResponse object. It returned None instead.

救命啊!

kkih6yb8

kkih6yb81#

它没有验证你的密码{'password_mismatch': 'The two password fields didn’t match.'}由于形式上你是如何extending your form,所以只需替换为下面的代码:
forms.py

class CustomUserCreationForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ("username", "email", "password1", "password2")

    def save(self):
        user = super(UserCreationForm, self).save(commit=False)
        user.email = self.cleaned_data["email"]
        user.save()
        return user
z18hc3ub

z18hc3ub2#

我用尼科的代码和一些其他的东西弄明白了。Django实际上在工作,我输入了错误的数据。Django会抛出“The view main.views.register didn't return an HttpResponse object.当我尝试注册一个现有用户时,它返回None instead”错误,该用户已添加。所以我一直使用“testuser”作为用户名,没有意识到它正在按预期工作。你必须每次输入一个唯一的用户名,否则Django返回“None”,这意味着该帐户已经注册。
我也不得不调整我的观点一点。下面是工作的“register”函数:

def register(request):
    if request.method == 'GET':
        return render(
            request, 'users/register.html',
            {'form': CustomUserCreationForm}
        )
    elif request.method == 'POST':
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            auth_login(request, user)
            return render(request, 'users/dashboard.html') 
        else:
            return HttpResponse('<h1>Invalid</h1>')

这一点,再加上将Niko的代码添加到forms.py,就是我所需要的:
forms.py:

# main/forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class CustomUserCreationForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ("username", "email", "password1", "password2")

    def save(self):
        user = super(UserCreationForm, self).save(commit=False)
        user.email = self.cleaned_data["email"]
        user.save()
        return user

请注意,我还必须在顶部添加from django.contrib.auth.models import User

相关问题