python django超链接

2022/6/9 1:21:30

本文主要是介绍python django超链接,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

之前用django框架打了一个简易的博客网站,现在说说怎么用django做超链接。
本文基于之前讲解的博客应用,如果只想学超链接请自行删减代码或评论提问。
首先,在templates文件夹下添加details.html文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ data.title }}</title>
</head>
<body>
    <h2>{{ data.title }}</h2>
    <img style="width: 450px;height: 300px;" src="{{ data.img }}">
</body>
</html>

然后,再添加menu.html文件:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Carton</title>
</head>
<body>
    <ul>
        {% for item in data %}
            <li>
                <a href="/details/{{ item.id }}">{{ item.title }}</a>
            </li>
        {% endfor %}
    </ul>
</body>
</html>

切记,html文件不能有中文!!!不然UTF-8编码会出错,页面会显示UnicodeError。

然后就开始建立连接了:
先打开views.py;

from django.shortcuts import render,redirect,render_to_response
from blog.models import BlogsPost


# Create your views here.

def blog_index(request):
    blog_list = BlogsPost.objects.all()
    return render(request,'index.html', {'blog_list': blog_list})

def blog_school(request):
    return redirect('https://www.dlmu.edu.cn/')


def details_render(response, id):
    data = {
        "1": {"title": "one",
              'img': 'http://photocdn.sohu.com/20140303/Img395937155.jpg'},
        "2": {"title": "two",
              'img': 'http://p4.so.qhmsg.com/sdr/400__/t01145220e19e14dd69.jpg'},
        "3": {"title": "three",
              'img': 'http://uploads.5068.com/allimg/1812/224-1Q21Q51239.jpg'},
        "4": {"title": "four",
              'img': 'http://www.chinaqw.com/zhwh/2016/09-06/U682P894T5D102134F42DT20160906113524.jpg'},
        "5": {"title": "five",
              'img': 'https://p1.ssl.qhmsg.com/t01409ee9dd99712d8c.jpg'}
    }.get(id)
    return render_to_response("details.html", locals())


def menu_list(request):
    data = [
        {"id": 1, "title": "The Chinese dream"},
        {"id": 2, "title": "Core socialist values"},
        {"id": 3, "title": "Reform and opening up"},
        {"id": 4, "title": "The Belt and Road"},
        {"id": 5, "title": "Dalian Maritime University"}
    ]
    return render_to_response("menu.html", locals())

接下来添加URL:
打开urls.py:

from django.conf.urls import url
from django.urls import path,re_path
from django.contrib import admin
from blog import views

urlpatterns = [
   url('admin/', admin.site.urls),
   url(r'^blog/$',views.blog_index,name='index'),
   url(r'^school/$',views.blog_school),
   path('menu_list/',views.menu_list),
   re_path(r'details/(?P<id>\d{1,2})',views.details_render),
]

这是运行程序,输入 http://127.0.0.1:8000/menu_list 即可打开超链接。



这篇关于python django超链接的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程