jwh5566
2017-10-01
python,django, ajax
base.html
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
</head>
<body>
{% block content%}{% endblock %}
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
{% block javascript %}{% endblock %}
</body>
</html>
示例 views.py
from django.contrib.auth.forms import UserCreationForm
from django.views.generic.edit import CreateView
class SignUpView(CreateView):
template_name = 'core/signup.html'
form_class = UserCreationForm
url.py
from django.conf.urls import url
from core import views
urlpatterns = [
url(r'^signup/$', views.SignUpView.as_view(), name='signup'),
]
signup.html
{% extends 'base.html' %}
{% block content %}
<div class="container">
<h1>Ajax View</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary">Sign up</button>
</form>
</div>
{% endblock %}
signup.html
{% extends 'base.html' %}
{% block javascript %}
<script>
$("#id_username").change(function () {
console.log( $(this).val() );
});
</script>
{% endblock %}
{% block content %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Sign up</button>
</form>
{% endblock %}
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()
}
return JsonResponse(data)
urls.py
from django.conf.urls import url
from core import views
urlpatterns = [
url(r'^signup/$', views.SignUpView.as_view(), name='signup'),
url(r'^ajax/validate_username/$', views.validate_username, name='validate_username'),
]
signup.html
{% extends 'base.html' %}
{% block javascript %}
<script>
$("#id_username").change(function () {
var username = $(this).val();
$.ajax({
url: '/ajax/validate_username/',
data: {
'username': username
},
dataType: 'json',
success: function (data) {
if (data.is_taken) {
alert("A user with this username already exists.");
}
}
});
});
</script>
{% endblock %}
{% block content %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Sign up</button>
</form>
{% endblock %}
$.ajax({
url: '{% url "validate_username" %}',
...
});
在视图函数中判断is_taken结果
if data['is_taken']:
data['error_message'] = 'A user with this username already exists.'
return JsonResponse(data)
signup.html
if (data.is_taken) {
alert(data.error_message);
}