Django开发(二)---加载网页效果

方法一:

1.建立一个static文件存放各种效果文件

2.在setting设置加载路径

STATICFILES_DIRS=(
    os.path.join(BASE_DIR,"static"),
)

3.设置别名,方便后期修改

STATIC_URL = '/static/'  

方法二:

{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {% load staticfiles %}
    <title>Title</title>
</head>
<body>
<script src="{% static 'jquery-3.3.1.min.js' %}" ></script>
<p>hello  {{time}}</p>
<script>
    $("p").css("color","red");
</script>
</body>

</html>

部署路由

from django.contrib import admin
from django.urls import path,re_path
from django.conf.urls import url
from blog import  views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('show_time/',views.show_time),
    url('article/(\d{4})', views.article),

    re_path('article/(\d{4})',views.article),
    path('article/<\d{4}>', views.article),

]

在url.py里面path或者url或者re_path来设置路由属性

要注意的是:
1、在Django1.x版本中自动导入:from django.conf.urls import include, url
而在Django2.0版本自动导入:from django.conf.urls import path
而不会导入“include”,这时需要我们在path后面手动导入:include。

2、path的用法和url有所不同:
url举例:
url(r’ ‘, include(‘names’, nameplace = ‘scores ‘))
path举例:
path(”, include((‘names’, scores’), namespace=’scores’))

2.X中,在Python正则表达式中,path命名式分组语法为 (?P<name>pattern) ,使用<>来实现分组,其中name为名称, pattern为待匹配的模式。这个与1.X的用法差不多,就是将1.X的url,改为re_path,
例子如上例把http://127.0.0.1:8000/article/2019网址,其中()把2019作为参数传给了views .py  article函数

from django.shortcuts import render,HttpResponse
import time

# Create your views here.
def show_time(request):#req表示用户的请求,必须加

    #必须返回http的响应
    t = time.localtime()
    return   render(request,"index.html",{"time":t})
    # return render(request,"Large_data/First_Page.html")


def  article(request,y):

    # return render(request,"index.html",{"time":y})
    return HttpResponse(y)

简易登陆界面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/register" method="post">
    <p>姓名<input type="text" name="user"></p>
        <p>年龄<input type="text" name="age"></p>
<p> <input type="submit">提交</p>
</form>

</body>

</html>
def register(request):
    # return HttpResponse("ok")
    # print(request.GET.get("user"))
    # print(request.GET.get("age"))
    if request.method=="POST":
        print(request.POST.get("user"))
        print(request.POST.get("age"))
        return HttpResponse("success")
    return render(request,"index.html")

注意:如果提交方式是post的话,需要在setting.py里将安全检测'django.middleware.csrf.CsrfViewMiddleware',注释掉

为了不把提交路径写死,可以设置别名

    path('register',views.register,name="reg"),
<form action={% url 'reg' %} method="post">

猜你喜欢

转载自blog.csdn.net/Lzs1998/article/details/88412596