美文网首页
首次踏进Django

首次踏进Django

作者: AndyDennisRob | 来源:发表于2020-02-25 11:50 被阅读0次

    前期准备

    下载好python,pycharm。
    记得把pip镜像设置为清华镜像或阿里云镜像(淘宝镜像).

    新建项目

    新建Django项目

    用pycharm新建Django项目。至于python “编译器”的设置这里就不赘述了。

    这里我们可以这样

    python manage.py runserver
    

    默认8000端口。当然,由于我是在pycharm中编写,直接run起来就行了,不用在命令行输入上述语句。
    不过要是指定某个端口,比如指定9090端口。可以这样

    python manage.py runserver 9090
    



    开始写代码

    接下来我们写个应用。

    python manage.py startapp blog
    
    项目目录

    记得在myblog目录(一开始新建项目的项目名称的目录)下的settings.py的INSTALLED_APPS添加刚刚添加的应用。

    添加的模块

    在blog目录下的views.py

    from django.shortcuts import render
    from django.http import HttpResponse
    
    # Create your views here.
    def index(request):
        return HttpResponse('hello django')
    

    然后在myblog的目录下更改urls.py文件

    from django.contrib import admin
    from django.urls import path
    import blog.views as bv
    
    urlpatterns = [
        path(r'admin/', admin.site.urls),
        path(r'index/', bv.index),
    ]
    

    运行然后在浏览器输入

    http://127.0.0.1:8000/index/
    

    即可看见页面返回hello django的字样。



    不过,当网站很庞大时,上面那样写并不科学。
    建议myblog目录下的urls.py改成如下

    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path(r'admin/', admin.site.urls),
        path(r'', include('blog.urls')),
    ]
    

    然后在blog页面下新建一个urls.py的文件。

    from django.urls import path
    from . import views
    
    urlpatterns = [
        path(r'blog/', views.index),
    ]
    

    在浏览器输入

    http://127.0.0.1:8000/blog/
    

    即可看到返回的"hello django"字样。

    项目介绍

    显然,现实场景下我们不单单会返回字符串。
    所以我们应该写多几个视图。
    在Django中我们应该写几个模板来让客户端访问。
    在应用的目录(这里是blog目录)下创建一个叫Templates的文件夹。
    最好在Templates下在新建一个文件夹,比如这里就叫blog的文件夹吧。

    层次关系

    这里我是跟着慕课网的杜秉轩老师的一视频跟着做的一个简易博客项目。
    不过这里要跟小伙伴提醒的是,老师用的是Django1.10,而笔者写这篇文章的时候的Django最新版本是2.0,会有一些用法上的不同。

    由于Django自带sqlite3的数据库,我们其实可以用pyCharm连接后看见数据库的可视化界面,不用装数据库,装可视化的软件。当然装也行。官网也有说明白。https://docs.djangoproject.com/en/3.0/ref/settings/#databases
    然后在myblog目录下的settings.py文件夹下更改即可。

    更改部分

    我们最先关注的是urls.py中的配置。(myblog/urls.py)

    from django.contrib import admin
    from django.urls import path, re_path, include
    
    urlpatterns = [
        path(r'admin/', admin.site.urls),
        re_path(r'blog/', include(('blog.urls', 'blog'), namespace='blog')),
    ]
    

    这里path,re_path都是2.0特有的。
    细心的小伙伴会发现这里其实include了blog应用中的urls的文件。
    那我们再看看blog应用中的urls.py

    from django.urls import path, re_path
    from . import views
    
    urlpatterns = [
        path(r'', views.index),
        re_path(r'article/(?P<article_id>[0-9]+)$', views.article_page, name='article_page'),
        re_path(r'edit/(?P<article_id>[0-9]+)$', views.edit_page, name='edit_page'),
        re_path(r'edit/action/$', views.edit_action, name='edit_action'),
    ]
    

    这里我也不详细说每个的作用了。rep_path里面用的是正则表达是。
    views.xxxxxx这里是调用我们此目录下的views文件中的函数。(本项目所有响应都写成了函数,但其实Django的view中可以写成类)

    我们看一下views.py中的内容

    from django.shortcuts import render
    from django.http import HttpResponse
    from . import models
    
    
    # Create your views here.
    def index(request):
        # return HttpResponse('hello django')
        # return render(request, 'blog/index.html', {'dic': 'Hello world'})
        articles = models.Article.objects.all()
        return render(request, 'blog/index.html', {'articles': articles})
    
    
    def article_page(request, article_id):
        article = models.Article.objects.get(pk=article_id)
        return render(request, 'blog/article_page.html', {'article': article})
    
    
    def edit_page(request, article_id):
        if str(article_id) == '0':
            return render(request, 'blog/edit_page.html')
        article = models.Article.objects.get(pk=article_id)
        return render(request, 'blog/edit_page.html', {'article': article})
    
    
    def edit_action(request):
        title = request.POST.get('title', 'unnamed title')
        content = request.POST.get('content', 'unwritten content')
        article_id = request.POST.get('article_id', '0')
        if article_id == '0':
            models.Article.objects.create(title=title, content=content)
            articles = models.Article.objects.all()
            return render(request, 'blog/index.html', {'articles': articles})
    
        article = models.Article.objects.get(pk=article_id)
        article.title = title
        article.content = content
        article.save()
        return render(request, 'blog/article_page.html', {'article': article})
    

    这里返回响应。注意一下render函数,第一个参数是请求,第二个参数是要响应的模板页面,第三个参数用来传给模板页面,实现从数据库获取的值渲染在模板页面中。

    总的目录是这样子,大家自行忽略note.html,那个是我临时记笔记用的。


    目录结构

    下面我们一次看看模板的写法
    article_page.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Article page</title>
        <style>
            body {
                background: #ffffea;
                margin-top: 100px;
                text-align: center;
            }
    
            .title {
                color: #62ffb0;
                margin-top: 10px;
                border: 1px solid aqua;
                width: 300px;
                display: inline-block;
            }
    
            .content {
                color: blueviolet;
                margin-top: 50px;
                margin-left: 10px;
                margin-right: 10px;
                border: 1px solid #62ffb0;
                min-height: 20vh;
            }
    
            .changeArticle{
                color: #bc6734;
                text-decoration: none;
                border: 1px solid aquamarine;
            }
        </style>
    </head>
    <body>
    <h1 class="title">{{ article.title }}</h1>
    <h3 class="content">{{ article.content }}</h3>
    <h3 class="changeArticle"><a href="edit/{{ article.id }}">ä¿®æ”¹æ–‡ç« </a></h3>
    </body>
    </html>
    



    edit_page.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Edit page</title>
        <style>
            body {
                background: #ffffea;
                margin-top: 100px;
                text-align: center;
            }
    
            .title{
                min-height: 30px;
                text-align: center;
                font-size: 30px;
            }
    
            .contentLabel{
                color: #91ffdb;
            }
    
            .content {
                margin-top: 10px;
                border: 0;
                border-radius: 5px;
                background-color: rgba(241, 241, 241, .98);
                height: 100px;
                padding: 10px;
                resize: none;
                min-height: 50vh;
                width: 900px;
                font-size: 25px;
                text-align: left;
            }
    
            .button{
                margin-top: 20px;
                width: 300px ;
            }
        </style>
    </head>
    <body>
    <form action="{% url 'blog:edit_action' %}" method="post">
        {% csrf_token %}
        <input type="hidden" name="article_id" value="{{ article.id | default:'0' }}"/>
        <label>文章标题
            <input class="title" type="text" name="title" value="{{ article.title }}"/>
        </label>
        <br>
        <p class="contentLabel">文章内容</p>
        <label>
    {#        <input type="text" name="content" value="{{ article.content }}"/>#}
            <textarea class="content" name="content">
                {{ article.content }}
            </textarea>
        </label>
        <br>
        <input class="button" type="submit" value="提交"/>
    </form>
    </body>
    </html>
    



    index.html

    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>template index</title>
        <style>
            body {
                background: #ffffea;
                margin-top: 100px;
                text-align: center;
            }
    
            .title {
                color: #62ffb0;
                margin-top: 10px;
                border: 1px solid aqua;
                width: 300px;
                display: inline-block;
            }
    
            .content {
                color: blueviolet;
                margin-top: 50px;
                border: 1px solid #62ffb0;
                min-height: 20vh;
            }
    
            .newArticle{
                color: #bc6734;
                text-decoration: none;
                border: 1px solid aquamarine;
            }
        </style>
    </head>
    <body>
    <h1><a href="edit/{{ 0 }}" class="newArticle">æ–°æ–‡ç« </a></h1>
    {% for article in articles %}
        <a class="title" href="article/{{article.id}}">{{ article.title }}</a>
        <br>
    {% endfor %}
    </body>
    </html>
    





    Django是mvc架构的,自然与数据库的交互式通过models来实现的,我们写好models.py文件。

    from django.db import models
    
    
    # Create your models here.
    class Article(models.Model):
        title = models.CharField(max_length=32, default='Title')
        content = models.TextField(null=True)
        pub_time = models.DateTimeField(null=True)
    
        def __str__(self):
            return self.title
    

    然后在项目根目录下,打开终端,输入

    python manage.py makemigrations blog
    

    blog也可以省略,这里只有一个应用。然后再输入

    python manage.py migrate
    

    可以看到blog/migrations文件夹下

    blog/migrations文件夹
    我这里迁移了四次。



    最后要跟大家介绍的是admin模块,它可以让用户在管理界面操作数据库。
    我们要首先建立一个超级管理员账号。
    在项目的更目录下,输入终端命令

    python manage.py createsuperuser
    

    然后输入用户名和密码即可。

    接着看一下myblog目录下的admin.py。

    from django.contrib import admin
    from django.urls import path, re_path, include
    
    # from django.conf.urls import url, include
    
    urlpatterns = [
        path(r'admin/', admin.site.urls),
        re_path(r'blog/', include(('blog.urls', 'blog'), namespace='blog')),
    ]
    

    注意到这里urlpatterns中有一个path,我们在浏览器输入

    http://127.0.0.1:8000/admin
    

    这里用户名和密码我们输入刚刚注册的超级管理员账号。
    要是忘了的话呢,可以再注册一个超级管理员账号。


    验证页面 登录后主页
    article页面

    这里article显示的栏目是blog/admin.py规定的

    from django.contrib import admin
    
    from .models import Article
    
    
    class ArticleAdmin(admin.ModelAdmin):
        list_display = ('title', 'content', 'pub_time')
        list_filter = ('pub_time',)
    
    
    admin.site.register(Article, ArticleAdmin)
    

    list_display 规定了管理面板显示的效果。
    至此,项目完毕,本文也差不多和大家说再见咯。最后让大家看一下效果。(前端效果不是本项目的重点,大家可以慢慢去完善)


    博客主页
    文章详情页面
    修改和新建文章页面

    这里字的对齐方式有点问题。(出于时间问题和觉得前端部分不是这次我们学习的重点,先不修改了)

    谢幕词

    本文到这里就算结束啦。
    该文是笔者第一次用Django搭建web应用,可能会有些疏漏,欢迎大家指正。
    顺带一提,快开学了,小伙伴们,你们准备好开学了吗?

    相关文章

      网友评论

          本文标题:首次踏进Django

          本文链接:https://www.haomeiwen.com/subject/qovzqhtx.html