python - 为什么 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>
解决方案
如果没有数据传递, 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})
推荐阅读
- c# - 如何从集合中的属性中获取 nameof()?
- python - Python数据框格式化字符串
- bitmap - 如何从camerax获取位图?
- android - 在 Android 中使用 Hilt 后无法创建视图模型实例
- arrays - Laravel collect($array)->sortBy($value)->values() 显示在屏幕上
- python - 数据框中的向量化字符串搜索
- r - 改进 R 中的现有循环和延迟
- java - 用坐标、长度、宽度和角度计算矩形的中心
- python - 如何将 arg 从命令传递到子命令 Discord py
- c# - 将文件上传到 Blob 存储错误 get_NetworkTimeout 没有实现