django命名空间
from django.urls import path
from . import views
app_name = 'news'
urlpatterns = [
path('', views.news, name='news'),
path('news_detail/<news_id>/', views.news_detail, name='news_detail'),
path('news_list/', views.news_list, name='news_list'),
]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>新闻首页</p>
<p><a href="{% url 'news:news_detail' 1 %}">新闻详情页</a></p>
</body>
</html>
django的ajax
-
from表单 -get方式 <from action="/text/" method="get">
user: <input type="text">
pwd: <input type="text">
<input type="submit">
</from>
验证: def text_ajax(request):
if request.method == 'GET':
name = request.GET.get('name')
pw = request.GET.get('pw')
print(request.method)
print(name)
print(pw)
-
ajax方式 ajax在django中使用ajax困扰了我几天时间,get方式可以直接使用,post则同样需要获取csrftoken,由于没太注意django控制台显示出的信息,一直看的只是浏览器的信息,报的是500的错误,也就是服务器内部错误,我以为是无法找到路由,结果网上查了几天,都没有结果,今天偶然间看到控制台信息,才知道是scrftoken没有携带。
-
urls中 from django.urls import path
from . import views
app_name = 'text_ajax'
urlpatterns = [
path('text/', views.text_ajax, name='text_ajax'),
]
-
html <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<h3>功能1:发送ajax请求</h3>
<p class="content"></p>这里的内容是空的
<button class="btn">ajax</button>
<p>
<button id="btn">post</button>
</p>
<script>
$('.btn').click(function () {
$.ajax({
url: '/text/text/',
type: 'get',
data: {name: 'zs', pw: "123"},
success: function (data) {
console.log(data)
}
})
})
function getCookie(name) {
var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
return r ? r[1] : undefined;
}
$('#btn').click(function () {
$.ajax({
url: '/text/text/',
type: 'post',
data: {name: 'zs', pw: "123"},
success: function (data) {
console.log(data)
$('.content').html(data)
},
headers: {
"X-CSRFToken": getCookie("csrftoken")
},
})
})
</script>
</body>
</html>
-
views from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
import json
def index(request):
return render(request, "text_ajax.html")
def text_ajax(request):
if request.method == 'GET':
name = request.GET.get('name')
pw = request.GET.get('pw')
print(request.method)
print(name)
print(pw)
elif request.method == 'POST':
name = request.POST.get('name')
pw = request.POST.get('pw')
print(request.method)
print(name)
print(pw)
return HttpResponse("hello world!")
return JsonResponse({"data": "hello world!"})
|