• django入门与实践


    第一种方法:

    在myblog/urls.py模块中:

    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('blog1/', include(('blog1.urls', 'a'), namespace='blogg')),  #'a'可以为任意字符,但不能为空
    ]
    myblog/urls.py

    在blog/urls.py模块中:

    from django.urls import path
    from . import views
    urlpatterns = [
        path('', views.index),  # 这是路由模式
        path('article/<int:article_id>', views.article_page, name='article_detai'),  # path中的组名必须和参数名一致
    ]
    blog/urls.py

    在blog/templates/index.html模板中:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1>
            <a href="">添加新文章</a>
        </h1>
        {% for article in articles %}
            <h2>
                <a href="{% url 'blogg:article_detai' article.id %}">{{ article.title }}</a>
            </h2>
        {% endfor %}
    </body>
    </html>
    blog/templates/index.html

    在blog/view.py模块中:

    from django.shortcuts import render
    from blog1 import models
    
    # 方法:index()
    # 参数:request:
    # 功能:将Article表中的数据取出,在页面上显示所有文章
    def index(request):
        
        articles = models.Article.objects.all()
        return render(request, 'blog1/index.html', {'articles': articles})
    
    
    # 方法:article_page()
    # 参数:request:
    #      article_id:文章id,唯一标识符
    # 功能:通过接收article_id,显示对应文章的详细内容
    def article_page(request, article_id):
    
        article = models.Article.objects.get(pk=article_id)
        return render(request, 'blog1/article_detail.html', {'article': article})
    blog/view.py

    第二种方法:

  • 相关阅读:
    codechef Taxi Driver
    BZOJ2190 SDOI2008 仪仗队
    BZOJ 1070: [SCOI2007]修车
    BZOJ 1066 [SCOI2007]蜥蜴
    最大流模板
    表达式计算
    codechef Polo the Penguin and the Tree
    LCA 求 树中两个点的距离
    Baby Step Giant Step model
    POJ 1330 Nearest Common Ancestors (LCA,dfs+ST在线算法)
  • 原文地址:https://www.cnblogs.com/chenjianfeng/p/10579815.html
Copyright © 2020-2023  润新知