Python爬蟲實戰(zhàn)筆記_4-1 Django Entrance

Step by step, my first django app
  1. Django startproject.
$ django-admin startproject mysite
  1. Django startapp.
$ cd mysite
$ python3 manage.py startapp myapp ### 環(huán)境中2.7與3.5版本并存,這里需要指明python3
  1. Go to pycharm, find settings.py, add app name 'myapp' into INSTALLED_APPS list.
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',  ###
]
  1. Create a new directory 'templates'(與manage.py同級), and add this directory into settings.py.
    If 'APP_DIRS' is True,It tells Django engine that you should look for templates inside installed applications besides the base DIR. If False, then the engine only search mysite/templates.
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR), 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
  1. New a file 'index.html' under 'templates'. Design it.
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div class="header">
        Welcome Django!
    </div>
    <div class="footer">
        <p></p>
    </div>
</body>
</html>
  1. In views.py, define a function. It will return a rendered html
def menublog(request):
        return render(request, 'index.html')
  1. Go to urls.py, define the url to lead all urls beginning with 'index' to 'menublog' defined in vews.py
from myapp.views import menublog
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', menublog)
]
  1. python manage.py runserver
python3 manage.py migrate
python3 manage.py runserver localhost:9001
  1. visit 'http://localhost:9001/index/' and 'Welcome Django!' will show on your browser.

Congratulations!

關(guān)聯(lián)templates與靜態(tài)資源如CSS, img
  1. settings.py中添加靜態(tài)資源的路徑
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
  1. 新建一個與manage.py同級的目錄名稱為"static"
    此目錄下存放CSS, img等資源。

  2. 在templates 中引用靜態(tài)資源
    index.html的第一行添加如下語法加載靜態(tài)資源,同時將資源的引用路徑都替換為src="{% static 'images/0001.jpg' %}"類似的格式。

{% load static %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>The blah</title>
    <link rel="stylesheet" type="text/css" href="{% static 'css/homework.css' %}">
</head>
<body>
    <div class="header">
        ![]({% static 'images/blah.png' %})
        <ul class="nav">
            <li><a href="#" >home</a></li>
            <li><a href="#" >site</a></li>
            <li><a href="#" >other</a></li>
        </ul>
    </div>
    <div class="main-content">
        <h2>The Beach</h2>
        <hr>
        <ul class="photos">
            <li>
                ![]({% static 'images/0001.jpg' %})
            </li>
            <li>
                ![]({% static 'images/0004.jpg' %})
            </li>
            <li>
                ![]({% static 'images/0003.jpg' %})
            </li>
        </ul>
        <p>
            stretching from Solta to M1jets
        </p>
    </div>
    <div class="footer">
        <p>? Mugglecoding</p>
    </div>
</body>
</html>
Connect model

這一步實現(xiàn)從數(shù)據(jù)庫中獲取數(shù)據(jù)并填充到templates的指定位置。

  1. pip install mongoengine
  2. in setting.py, connect your model
# website是目標數(shù)據(jù)庫的名字
from mongoengine import connect
connect('website', host='127.0.0.1', port=27017)
  1. go to models.py to define your own model
from django.db import models
from mongoengine import *
#  Create your models here.
class menublog(Document):
      des = StringField()
      title = StringField()
      score = StringField()
      tags = ListField(StringField())
      author = StringField()
      # targettable 指定數(shù)據(jù)庫website中的一張數(shù)據(jù)表的名字
      meta = {
        'collection': 'targettable'
    }
  1. in views.py, import your model
    render() combines a given template with a given context dictionary and returns an HttpResponse object with that rendered text.
# 導入models.py中定義的class menublog
from myapp.models import menublog
def myview(request):
      data = menublog.objects
      # mydata將作為key在templates中被引用
      context = {    
         'mydata': data}
      return render(request, 'index.html', context)
  1. Django template language
    引用views.py中myview返回的HttpResponse
......
           {% for item in mydata %}
                <li>
                    ![]({% static 'images/0001.jpg' %})
                    <div class="article-info">
                        <h3><a href="#">{{ item.title }}</a></h3>
                        <p class="meta-info">
                            {% for tag in item.tags %}
                                <span class="meta-cate">{{ tag }}</span>
                            {% endfor %}
                        </p>
                        <p class="description">{{ item.des }}</p>
                    </div>
                    <div class="rate">
                        <span class="rate-score">{{ item.score }}</span>
                    </div>
                </li>
           {% endfor %}
......

就像直接使用python一樣,for循環(huán)也可以嵌套。

至此,對Django的整個框架結(jié)構(gòu)有了初步的印象。
Keep going...

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容