表单 disabled/enable 按钮 django python
Forms disabled/enable button django python
我在注册站点时遇到问题。我想制作注册面板,我想添加当密码和密码确认相等且不为空时启用注册按钮提交表单后....但我真的不知道该怎么做。有人可以帮我吗?
这是我的代码:
signup.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="{% url 'sign_upsucces' %}" >
{% csrf_token %}
{{ form }}
{{ fail }}
<button type = 'submit' {{ some }}>Zarejestruj się</button>
</form>
</html>
views.py
def sign_upsucces(request):
form = SignUpForm(request.POST or None)
users = SignUp()
people = SignUp.objects.all()
fail = ''
some = 'disabled'
if form.is_valid():
dane = form.save(commit=False)
if (len(people)>0):
try:
person = SignUp.objects.get(login = dane.login)
except SignUp.DoesNotExist:
if dane.password == dane.password_confirm:
users.login = dane.login
users.password = dane.password
users.password_confirm = dane.password_confirm
users.save()
some = '<button type="submit">Zarejestruj się</button>'
fail = 'Konto utworzone!'
session = 'Zaloguj się'
else:
fail = 'Hasła się nie zgadzają'
else:
fail = 'Istnieje'
session = 'Zaloguj się'
else:
if dane.password == dane.password_confirm:
user = SignUp()
user.login = dane.login
user.password = dane.password
user.password_confirm = dane.password_confirm
user.save()
fail = 'Konto utworzone'
session = 'Zaloguj się'
return render(request, 'signup.html', {'form':form, 'dane':dane, 'fail':fail, 'some':some, 'session':session})
forms.py
class SignUpForm(ModelForm):
class Meta:
model = SignUp
fields =['login','password','password_confirm']
models.py
from django.db import models
class SignUp(models.Model):
login = models.CharField(max_length=100, blank = False, default="")
password = models.CharField(max_length=100, blank=False)
password_confirm = models.CharField(max_length=100, blank=False)
非常感谢您的帮助。我已经搜索了很多,但找不到。
提前谢谢您!
娜塔莉亚
您可以为 SignUpForm
创建自定义清理方法 - 请参阅 Cleaning a specific field attribute。
对于 login
字段,您必须创建 clean_login
方法,对于 password_confirm
字段,您必须创建 clean_password_confirm
方法。
因此您可以执行以下操作。
forms.py:
from django.core.exceptions import ValidationError
from .models import SignUp
class SignUpForm(ModelForm):
class Meta:
model = SignUp
fields =['login','password','password_confirm']
def clean_login(self):
login = self.cleaned_data.get("login")
# Check SignUp Exists
if SignUp.objects.filter(login=login).exists():
raise ValidationError("The same login is exist!")
return login
def clean_password_confirm(self):
password = self.cleaned_data.get("password")
password_confirm = self.cleaned_data.get("password_confirm")
# Verify passwords
if password and password_confirm and password != password_confirm:
raise ValidationError("Password mismatch!")
return password_confirm
views.py:
def sign_upsucces(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
# Form is valid
# So SignUp login is not exists
# password confirmed and the same
# With calling save() , You create an object
signup_object = form.save()
# <b>Add here some messages for the user</b>
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
在HTML中我们可以使用form.as_p()
、as_ul()
或as_table()
- 见 Outputting forms as HTML
.html:
<form method="post" action="{% url 'sign_upsucces' %}" >
{% csrf_token %}
{# RENDER FORM as a series of <p> tags. #}
{# You will also see ther errors if form is not valid #}
{{ form.as_p }}
<button type='submit'>Zarejestruj się</button>
</form>
我不确定这是否可以直接通过 django 表单完成,但您可以添加自定义 javascript 代码以获得所需的结果。
在 django 表单中,除非您明确指定,否则所有输入字段都根据其在 models
或 forms
中的字段名称分配为 id_<field name>
。
牢记这一点,我们可以将自定义 js 写入 enable/disable 提交按钮。
您需要按如下方式更新您的模板
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="{% url 'sign_upsucces' %}" >
{% csrf_token %}
{{ form }}
{{ fail }}
<button type = 'submit' id="submit_button" disabled {{ some }}>Zarejestruj się</button>
</form>
<script>
// create a list of id of items we will be attaching events to
let items = ['id_password', 'id_password_confirm', 'submit_button']
// get all items by id from items array
let [password, password_confirm, button] = items.map((item) => document.getElementById(item))
// add onkeyup eventlistener to all the input fields
password.onkeyup = password_confirm.onkeyup = validator;
// create validation function which will enable/disable submit button
function validator(){
button.disabled = !(password.value && (password.value === password_confirm.value))
}
</script>
</html>
在上面的代码中,我通过它们的 id 访问了密码字段和按钮,并基于它们编写了 js 代码。查看代码中的注释以了解有关其工作原理的更多信息。
注意:我添加了最少的验证,即密码和 password_confirm 应该相等且不为空。你可以根据你的需要扩展它。
我在注册站点时遇到问题。我想制作注册面板,我想添加当密码和密码确认相等且不为空时启用注册按钮提交表单后....但我真的不知道该怎么做。有人可以帮我吗? 这是我的代码: signup.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="{% url 'sign_upsucces' %}" >
{% csrf_token %}
{{ form }}
{{ fail }}
<button type = 'submit' {{ some }}>Zarejestruj się</button>
</form>
</html>
views.py
def sign_upsucces(request):
form = SignUpForm(request.POST or None)
users = SignUp()
people = SignUp.objects.all()
fail = ''
some = 'disabled'
if form.is_valid():
dane = form.save(commit=False)
if (len(people)>0):
try:
person = SignUp.objects.get(login = dane.login)
except SignUp.DoesNotExist:
if dane.password == dane.password_confirm:
users.login = dane.login
users.password = dane.password
users.password_confirm = dane.password_confirm
users.save()
some = '<button type="submit">Zarejestruj się</button>'
fail = 'Konto utworzone!'
session = 'Zaloguj się'
else:
fail = 'Hasła się nie zgadzają'
else:
fail = 'Istnieje'
session = 'Zaloguj się'
else:
if dane.password == dane.password_confirm:
user = SignUp()
user.login = dane.login
user.password = dane.password
user.password_confirm = dane.password_confirm
user.save()
fail = 'Konto utworzone'
session = 'Zaloguj się'
return render(request, 'signup.html', {'form':form, 'dane':dane, 'fail':fail, 'some':some, 'session':session})
forms.py
class SignUpForm(ModelForm):
class Meta:
model = SignUp
fields =['login','password','password_confirm']
models.py
from django.db import models
class SignUp(models.Model):
login = models.CharField(max_length=100, blank = False, default="")
password = models.CharField(max_length=100, blank=False)
password_confirm = models.CharField(max_length=100, blank=False)
非常感谢您的帮助。我已经搜索了很多,但找不到。 提前谢谢您!
娜塔莉亚
您可以为 SignUpForm
创建自定义清理方法 - 请参阅 Cleaning a specific field attribute。
对于 login
字段,您必须创建 clean_login
方法,对于 password_confirm
字段,您必须创建 clean_password_confirm
方法。
因此您可以执行以下操作。
forms.py:
from django.core.exceptions import ValidationError
from .models import SignUp
class SignUpForm(ModelForm):
class Meta:
model = SignUp
fields =['login','password','password_confirm']
def clean_login(self):
login = self.cleaned_data.get("login")
# Check SignUp Exists
if SignUp.objects.filter(login=login).exists():
raise ValidationError("The same login is exist!")
return login
def clean_password_confirm(self):
password = self.cleaned_data.get("password")
password_confirm = self.cleaned_data.get("password_confirm")
# Verify passwords
if password and password_confirm and password != password_confirm:
raise ValidationError("Password mismatch!")
return password_confirm
views.py:
def sign_upsucces(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
# Form is valid
# So SignUp login is not exists
# password confirmed and the same
# With calling save() , You create an object
signup_object = form.save()
# <b>Add here some messages for the user</b>
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
在HTML中我们可以使用form.as_p()
、as_ul()
或as_table()
- 见 Outputting forms as HTML
.html:
<form method="post" action="{% url 'sign_upsucces' %}" >
{% csrf_token %}
{# RENDER FORM as a series of <p> tags. #}
{# You will also see ther errors if form is not valid #}
{{ form.as_p }}
<button type='submit'>Zarejestruj się</button>
</form>
我不确定这是否可以直接通过 django 表单完成,但您可以添加自定义 javascript 代码以获得所需的结果。
在 django 表单中,除非您明确指定,否则所有输入字段都根据其在 models
或 forms
中的字段名称分配为 id_<field name>
。
牢记这一点,我们可以将自定义 js 写入 enable/disable 提交按钮。
您需要按如下方式更新您的模板
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="{% url 'sign_upsucces' %}" >
{% csrf_token %}
{{ form }}
{{ fail }}
<button type = 'submit' id="submit_button" disabled {{ some }}>Zarejestruj się</button>
</form>
<script>
// create a list of id of items we will be attaching events to
let items = ['id_password', 'id_password_confirm', 'submit_button']
// get all items by id from items array
let [password, password_confirm, button] = items.map((item) => document.getElementById(item))
// add onkeyup eventlistener to all the input fields
password.onkeyup = password_confirm.onkeyup = validator;
// create validation function which will enable/disable submit button
function validator(){
button.disabled = !(password.value && (password.value === password_confirm.value))
}
</script>
</html>
在上面的代码中,我通过它们的 id 访问了密码字段和按钮,并基于它们编写了 js 代码。查看代码中的注释以了解有关其工作原理的更多信息。
注意:我添加了最少的验证,即密码和 password_confirm 应该相等且不为空。你可以根据你的需要扩展它。