首页 > 解决方案 > 为什么 Django 来自 Invalid?

问题描述

我创建了一个 Django 表单。我还在表单字段中插入了有效值,但仍然出现表单无效错误。我昨天使用了相同的代码,它工作正常,但我不知道为什么它给出了无效错误,这可能是什么原因?

这是我的代码:View.py

from django.shortcuts import render,redirect
from django.views.generic import View,TemplateView
from .forms import Registration_Form
from .models import User_Registration
from django.contrib import messages

# Create your views here.

class MainPageView(TemplateView):
    template_name='main.html'

class LoginView(TemplateView):
    template_name='login.html'

def RegistrationView(request):
    form=Registration_Form()
    if request.method=='POST':
        print(request.POST)
        if form.is_valid():
            form.save()
            print("Valid")
            return redirect('login_view')
        else:
            print("Not Valid")
            # messages.error(request,"Form is Invalid!")
            return redirect('registration_view')

    else:
        return render(request,'registration.html',{'form':form})
    
   
    # template_name='registration.html'

表格.py

from django import forms
from .models import User_Registration
class Registration_Form(forms.ModelForm):
    class Meta:
        model=User_Registration
        fields=('company_name','username','password','email')

        widgets={
            'company_name':forms.TextInput(attrs={'class':'form-control input-sm'}),
            'username':forms.TextInput(attrs={'class':'form-control'}),
            'password':forms.PasswordInput(attrs={'class':'form-control'}),
            'email':forms.EmailInput(attrs={'class':'form-control'}),
        }

注册.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
  <div class="form-group">
    <br><br><br>
    <h2 style="padding-left: 480px;">Registration Form</h2>
    <br>
  <form method="POST" action="">

    {{form.as_p}}
    {% csrf_token %}

    <input type="submit" value="Submit">
  </form>
</div>
</body>
</html>

标签: pythondjango

解决方案


如果没有数据传递, Aform总是无效的。因此,您需要在构造表单时传递request.POST(也许是):request.FILES

def RegistrationView(request):
    if request.method == 'POST':
        form = Registration_Form(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            print('Valid')
            return redirect('login_view')
        else:
            print('Not Valid')
    else:
        form = RegistrationForm()
    return render(request,'registration.html',{'form':form})

推荐阅读