Django基础(一):views-URL

[TOC]

settings.py
INSTALL_APPS 中添加新建的app,让django自动找到app中的模板文件(app-name/templates/下的文件)和静态文件(app-name/static/中的文件)

from learn import views as learn_views
from . import views

demo0

def add(request):
    a = request.GET['a']
    b = request.GET['b']
    c = int(a)+int(b)
    return HttpResponse(str(c))
# 127.0.0.1:8000/learn/add/?a=1&b=5
# 浏览器手动以GET方式访问 后台执行add方法
def add2(request, a, b):
    c = int(a) + int(b)
    return HttpResponse(str(c))

demo1

# suynblog/learn/views.py
def add2(request,a,b):
    c = int(a)+int(b)
    return HttpResponse(str(c))
# suynblog/learn/urls.py
    url(r'^add2/(\d+)/(\d+)/$',views.add2,name="add2"),
    url(r'^add3/(?P\d+)/(?P\d+)/$',views.add2,name="add3"),
  • views test
$python manage.py shell
In [1]: from django.urls import reverse

In [2]: reverse('learn:add2',args=(33,22))
Out[2]: u'/learn/add2/33/22/'

In [3]: reverse('learn:add3',args=(33,22))
Out[3]: u'/learn/add3/33/22/'
  • html test
    计算4+5
    计算4+5

这里,name属性 可以用于在 templates, models, views ……中得到对应的网址,相当于“给网址取了个名字”,只要这个名字不变,网址变了也能通过名字获取到。add2位置参数、add3关键字参数,URL正则变了,只要name不变,test中的url就不变,不过实际地址栏请求url是根据正则来改变的。假设无聊想要地址栏显示新的url不过执行同样的url就可以代码中用reverse实现,如demo2。

demo2

# views.py
def sum(request,a,b):
    c = int(a)+int(b)
    return HttpResponse(str(c))
def old_sum_redirect(request,a,b):
    return HttpResponseRedirect(reverse('learn:sum',args=(a,b)))
# urls.py
    url(r'^sum/(?P\d+)/(?P\d+)/$',views.old_sum_redirect,name="old_sum"),
    url(r'^new_sum/(?P\d+)/(?P\d+)/$',views.sum,name="sum"),
# sum.html
    sum:4+5

这里,链接sum:4+5,请求的是'sum/4/5'却会自动跳转到'new_sum/4/5'。

你可能感兴趣的:(Django基础(一):views-URL)