Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么form.is_valid()在UserCreationForm、Django中始终为false_Python_Django - Fatal编程技术网

Python 为什么form.is_valid()在UserCreationForm、Django中始终为false

Python 为什么form.is_valid()在UserCreationForm、Django中始终为false,python,django,Python,Django,我在Django注册。当我访问register/page时,所有内容都显示良好,并且没有任何错误消息。但是,我注册的用户没有保存在Django的数据库中(在管理页面上找不到该用户)。另外,重定向也不起作用。 因此,我认为“form.is\u valid()总是false”是问题所在 有什么问题 我怎样才能解决这个问题 这是view.py from django.shortcuts import render, redirect from django.http import HttpRespon

我在Django注册。当我访问register/page时,所有内容都显示良好,并且没有任何错误消息。但是,我注册的用户没有保存在Django的数据库中(在管理页面上找不到该用户)。另外,重定向也不起作用。 因此,我认为“
form.is\u valid()
总是false”是问题所在

  • 有什么问题
  • 我怎样才能解决这个问题
  • 这是view.py

    from django.shortcuts import render, redirect
    from django.http import HttpResponse
    
    from django.views.generic import TemplateView, CreateView
    from django.contrib.auth.mixins import LoginRequiredMixin
    
    from .forms import SignUpForm
    from django.urls import reverse_lazy
      
    from .models import *
    from django.contrib import messages
    
    
    class HomeView(TemplateView):
        template_name = 'common/home.html'
    
    class DashboardView(TemplateView):
        template_name = 'common/dashboard.html'
        login_url = reverse_lazy('login')
    
    # class SignUpView(CreateView):
    #     form_class = SignUpForm
    #     success_url = reverse_lazy('home')
    #     template_name = 'common/register.html'
    
    
    def register(request):
        form = SignUpForm()
    
        if request.method=='POST':
            form = SignUpForm(request.POST)
            if form.is_valid():
                form.save()
                username = form.cleaned_data.get('username')
                return redirect('login') 
    
        context = {'form': form}          
        return render(request, 'common/register.html', context)
    
    
    from django.contrib.auth import authenticate, login
    
    
    
    def user_login(request):
    
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
    
            user = authenticate(request, username=username, password=password)
            
    
            if user is not None:
                login(request, user)
                return redirect('dashboard')
            else:
                return render(request, 'common/login.html', {'error' : 'username or password is incorrect.'})
        else:
            return render(request, 'common/login.html')
    
    from django import forms
    from django.contrib.auth.models import User
    from django.contrib.auth.forms import UserCreationForm
    
    
    class SignUpForm(UserCreationForm):
    
        first_name = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your first name'}))
        last_name = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your last name'}))
        email = forms.EmailField(max_length=254, required=False, help_text='Enter a valid email address', widget=forms.EmailInput(attrs={'placeholder': 'Your email'}))
        # student_ID = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your student ID'}))
        # CBNU_PW = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your CBNU PW'}))
        password = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Password'}))
        password2 = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Repeat your password'}))
    
    
        class Meta:
            model = User
            widgets = {
                'username': forms.TextInput(attrs={'placeholder': 'Username'})
            }
            fields = [
                'username', 
                'first_name', 
                'last_name', 
                'email', 
                # 'student_ID',
                # 'CBNU_PW',
                'password', 
                'password2', 
            ]
    
    from django.contrib import admin
    from django.shortcuts import redirect
    from django.urls import path
    from apps.common.views import DashboardView, user_login, HomeView, register
    from django.contrib.auth import views as auth_views
    
    
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('dashboard/', DashboardView.as_view(), name='dashboard'),
        path('', HomeView.as_view(), name='home'),
        path('register/', register, name='register'),
        
        path('login/', user_login, name='login'),
    
        path('logout/', auth_views.LogoutView.as_view(
            next_page='dashboard'
            ),
            name='logout'
        ),
    ]
    
    这是forms.py

    from django.shortcuts import render, redirect
    from django.http import HttpResponse
    
    from django.views.generic import TemplateView, CreateView
    from django.contrib.auth.mixins import LoginRequiredMixin
    
    from .forms import SignUpForm
    from django.urls import reverse_lazy
      
    from .models import *
    from django.contrib import messages
    
    
    class HomeView(TemplateView):
        template_name = 'common/home.html'
    
    class DashboardView(TemplateView):
        template_name = 'common/dashboard.html'
        login_url = reverse_lazy('login')
    
    # class SignUpView(CreateView):
    #     form_class = SignUpForm
    #     success_url = reverse_lazy('home')
    #     template_name = 'common/register.html'
    
    
    def register(request):
        form = SignUpForm()
    
        if request.method=='POST':
            form = SignUpForm(request.POST)
            if form.is_valid():
                form.save()
                username = form.cleaned_data.get('username')
                return redirect('login') 
    
        context = {'form': form}          
        return render(request, 'common/register.html', context)
    
    
    from django.contrib.auth import authenticate, login
    
    
    
    def user_login(request):
    
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
    
            user = authenticate(request, username=username, password=password)
            
    
            if user is not None:
                login(request, user)
                return redirect('dashboard')
            else:
                return render(request, 'common/login.html', {'error' : 'username or password is incorrect.'})
        else:
            return render(request, 'common/login.html')
    
    from django import forms
    from django.contrib.auth.models import User
    from django.contrib.auth.forms import UserCreationForm
    
    
    class SignUpForm(UserCreationForm):
    
        first_name = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your first name'}))
        last_name = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your last name'}))
        email = forms.EmailField(max_length=254, required=False, help_text='Enter a valid email address', widget=forms.EmailInput(attrs={'placeholder': 'Your email'}))
        # student_ID = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your student ID'}))
        # CBNU_PW = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your CBNU PW'}))
        password = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Password'}))
        password2 = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Repeat your password'}))
    
    
        class Meta:
            model = User
            widgets = {
                'username': forms.TextInput(attrs={'placeholder': 'Username'})
            }
            fields = [
                'username', 
                'first_name', 
                'last_name', 
                'email', 
                # 'student_ID',
                # 'CBNU_PW',
                'password', 
                'password2', 
            ]
    
    from django.contrib import admin
    from django.shortcuts import redirect
    from django.urls import path
    from apps.common.views import DashboardView, user_login, HomeView, register
    from django.contrib.auth import views as auth_views
    
    
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('dashboard/', DashboardView.as_view(), name='dashboard'),
        path('', HomeView.as_view(), name='home'),
        path('register/', register, name='register'),
        
        path('login/', user_login, name='login'),
    
        path('logout/', auth_views.LogoutView.as_view(
            next_page='dashboard'
            ),
            name='logout'
        ),
    ]
    
    这是url.py

    from django.shortcuts import render, redirect
    from django.http import HttpResponse
    
    from django.views.generic import TemplateView, CreateView
    from django.contrib.auth.mixins import LoginRequiredMixin
    
    from .forms import SignUpForm
    from django.urls import reverse_lazy
      
    from .models import *
    from django.contrib import messages
    
    
    class HomeView(TemplateView):
        template_name = 'common/home.html'
    
    class DashboardView(TemplateView):
        template_name = 'common/dashboard.html'
        login_url = reverse_lazy('login')
    
    # class SignUpView(CreateView):
    #     form_class = SignUpForm
    #     success_url = reverse_lazy('home')
    #     template_name = 'common/register.html'
    
    
    def register(request):
        form = SignUpForm()
    
        if request.method=='POST':
            form = SignUpForm(request.POST)
            if form.is_valid():
                form.save()
                username = form.cleaned_data.get('username')
                return redirect('login') 
    
        context = {'form': form}          
        return render(request, 'common/register.html', context)
    
    
    from django.contrib.auth import authenticate, login
    
    
    
    def user_login(request):
    
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
    
            user = authenticate(request, username=username, password=password)
            
    
            if user is not None:
                login(request, user)
                return redirect('dashboard')
            else:
                return render(request, 'common/login.html', {'error' : 'username or password is incorrect.'})
        else:
            return render(request, 'common/login.html')
    
    from django import forms
    from django.contrib.auth.models import User
    from django.contrib.auth.forms import UserCreationForm
    
    
    class SignUpForm(UserCreationForm):
    
        first_name = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your first name'}))
        last_name = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your last name'}))
        email = forms.EmailField(max_length=254, required=False, help_text='Enter a valid email address', widget=forms.EmailInput(attrs={'placeholder': 'Your email'}))
        # student_ID = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your student ID'}))
        # CBNU_PW = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your CBNU PW'}))
        password = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Password'}))
        password2 = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Repeat your password'}))
    
    
        class Meta:
            model = User
            widgets = {
                'username': forms.TextInput(attrs={'placeholder': 'Username'})
            }
            fields = [
                'username', 
                'first_name', 
                'last_name', 
                'email', 
                # 'student_ID',
                # 'CBNU_PW',
                'password', 
                'password2', 
            ]
    
    from django.contrib import admin
    from django.shortcuts import redirect
    from django.urls import path
    from apps.common.views import DashboardView, user_login, HomeView, register
    from django.contrib.auth import views as auth_views
    
    
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('dashboard/', DashboardView.as_view(), name='dashboard'),
        path('', HomeView.as_view(), name='home'),
        path('register/', register, name='register'),
        
        path('login/', user_login, name='login'),
    
        path('logout/', auth_views.LogoutView.as_view(
            next_page='dashboard'
            ),
            name='logout'
        ),
    ]
    
    这是关于register.html中表单的一些代码

    <form method="POST" action="" class="register-form" id="register-form">
                                {%csrf_token%}
                                <div class="form-group">
                                    <label for="username"><i class="zmdi zmdi-account material-icons-name"></i></label>
                                    {{form.username}}
                                </div>
                                <div class="form-group">
                                    <label for="first_name"><i class="zmdi zmdi-account material-icons-name"></i></label>
                                    {{form.first_name}}
                                </div>
                                <div class="form-group">
                                    <label for="last_name"><i class="zmdi zmdi-account material-icons-name"></i></label>
                                    {{form.last_name}}
                                </div>
                                <div class="form-group">
                                    <label for="email"><i class="zmdi zmdi-email"></i></label>
                                    {{form.email}}
                                </div>
                                <!-- <div class="form-group">
                                    <label for="student_ID"><i class="zmdi zmdi-email"></i></label>
                                    {{form.student_ID}}
                                </div>
                                <div class="form-group">
                                    <label for="CBNU_PW"><i class="zmdi zmdi-email"></i></label>
                                    {{form.CBNU_PW}}
                                </div> -->
                                <div class="form-group">
                                    <label for="password"><i class="zmdi zmdi-lock"></i></label>
                                    {{form.password}}
                                </div>
                                <div class="form-group">
                                    <label for="password2"><i class="zmdi zmdi-lock-outline"></i></label>
                                    {{form.password2}}
                                </div>
                                <div class="form-group">
                                    <input type="checkbox" name="agree-term" id="agree-term" class="agree-term" />
                                    <label for="agree-term" class="label-agree-term"><span><span></span></span>I agree all statements in  <a href="#" class="term-service">Terms of service</a></label>
                                </div>  
                                <div class="form-group form-button">
                                    <input type="submit" name="signup" id="signup" class="form-submit" value="Register"/>
                                </div>
    
    
    {%csrf_令牌%}
    {{form.username}
    {{form.first{u name}}
    {{form.last_name}
    {{form.email}
    {{form.password}}
    {{form.password2}}
    我同意所有的声明
    
    UserCreationForm
    具有密码字段
    password1
    password2
    ,但您使用
    password
    password2
    作为字段。您只需在继承这些声明时将其从表单中删除,并在模板中进行更正

    class SignUpForm(UserCreationForm):
    
        first_name = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your first name'}))
        last_name = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your last name'}))
        email = forms.EmailField(max_length=254, required=False, help_text='Enter a valid email address', widget=forms.EmailInput(attrs={'placeholder': 'Your email'}))
        # student_ID = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your student ID'}))
        # CBNU_PW = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Your CBNU PW'}))
        
        class Meta:
            model = User
            widgets = {
                'username': forms.TextInput(attrs={'placeholder': 'Username'})
            }
            fields = [
                'username', 
                'first_name', 
                'last_name', 
                'email', 
                # 'student_ID',
                # 'CBNU_PW',
            ] # declared fields don't need to be added in this list
    

    在模板中,将
    {{form.password}}
    更改为
    {{form.password1}}

    打印(form.errors)
    @WillemVanOnsem感谢您的帮助。我应该在哪里写代码?在您的视图下面的
    if form.is\u valid()
    子句(所以在
    上下文={'form':form}
    之前)。很抱歉,它不起作用。但是,非常感谢你的帮助!这不是解决问题,而是诊断问题。非常感谢!!!!成功了!谢谢你的帮助