我有一份注册表格
class RegistrationForm(UserCreationForm):
class Meta:
model = User
fields = (
'username',
'first_name',
'last_name',
'email',
'password1',
'password2',
)
email = forms.EmailField(required=True)
def __init__(self, *args, **kwargs):
super(UserCreationForm, self).__init__(*args, **kwargs)
self.fields['password1'].help_text = "Your password can't be too similar to your other personal information.Your password must contain at least 8 characters.Your password can't be a commonly used password.Your password can't be entirely numeric."
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
self.add_error('password1', 'Re-enter password')
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return password2
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
我想使用ajax检查用户名可用性:
views.py
from django.contrib.auth.models import User
from django.http import JsonResponse
def validate_username(request):
username = request.GET.get('username', None)
data = {
'is_taken': User.objects.filter(username__iexact=username).exists()
}
if data['is_taken']:
data['error_message'] = 'A user with this username already exists.'
return JsonResponse(data)
Register.HTML
{ extends 'base.html' %}
{% block javascript %}
<script>
$("#id_username").change(function () {
var form = $(this).closest("form");
$.ajax({
url: form.attr("data-validate-username-url"),
data: form.serialize(),
dataType: 'json',
success: function (data) {
if (data.is_taken) {
alert(data.error_message);
}
}
});
});
</script>
{% endblock %}
{% block content %}
<form method="post" data-validate-username-url="{% url 'validate_username' %}">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Sign up</button>
</form>
{% endblock %}
唯一的区别是我手动渲染了表单字段并使用了widget调整而不是
{{ form.as_p }}
我有
{% for hidden_field in form.hidden_fields %}
{{ hidden_field }}
{% endfor %}
{% if form.non_field_errors %}
<div class="alert alert-danger" role="alert">Danger alert</div>
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
{% endif %}
{% for field in form.visible_fields %}
<div class="form-group">
{{ field.label_tag }}
{% if form.is_bound %}
{% if field.errors %}
<div class="form-group has-error">
{% render_field field class="form-control" %}
</div>
{% for error in field.errors %}
<div class="errorlist">
{{ error }}
</div>
{% endfor %}
{% else %}
<div class="form-group has-success">
{% render_field field class="form-control" %}
</div>
{% endif %}
{% else %}
{% render_field field class="form-control" %}
{% endif %}
{% if field.help_text %}
<small class="form-text text-muted">{{ field.help_text }}</small>
{% endif %}
</div>
{% endfor %}
ajax请求正在运行,因为我在CMD中获取了具有相关字段数据的GET请求302。我唯一的问题是警报不起作用。
谢谢。