基于How To Tango With Django 1.9的重新实践(0-5)

我使用的Django版本为1.10,之前参照How To Tango With Django1.7做的乱七八糟的好是心烦,遂重新又做了一遍

新版本的文件树如下

C:.
├─.idea
│ └─inspectionProfiles
├─media
├─rango
│ ├─migrations
│ └─__pycache__
├─static
│ ├─css
│ ├─images
│ └─js
├─tango_with_django_project
│ └─__pycache__
└─templates
└─rango

这里写图片描述

tango_with_django_project/__init__.py文件内容如下

import pymysql

#初始化MySQL数据库
pymysql.install_as_MySQLdb()

tango_with_django_project/setting.py文件内容如下

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR=os.path.join(BASE_DIR, 'templates')
STATIC_DIR = os.path.join(BASE_DIR, 'static')
MEDIA_DIR = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = [STATIC_DIR, ]


MEDIA_ROOT = MEDIA_DIR

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'qpzp$-bape)6cn^t#ziu2wqa3to4plor3kr_69+g(l07zq#l8y'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rango',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'tango_with_django_project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR,]
        ,
        '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',
                'django.template.context_processors.media',
            ],
        },
    },
]

WSGI_APPLICATION = 'tango_with_django_project.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'tango_with_django_project',
        'USER': 'root',
        'PASSWORD': 'rootdjangotest',
        'HOST': '127.0.0.1',
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'
MEDIA_URL = '/media/'

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

tango_with_django_project/urls.py文件内容如下

from django.conf.urls import url,include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^rango/', include('rango.urls')),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

populate_rango.py文件内容如下

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
                       'tango_with_django_project.settings')

import django
django.setup()
from rango.models import Category, Page

def populate():

    python_pages = [
        {"title": "Official Python Tutorial",
         "url":"http://docs.python.org/2/tutorial/"},
        {"title":"How to Think like a Computer Scientist",
         "url":"http://www.greenteapress.com/thinkpython/"},
        {"title":"Learn Python in 10 Minutes",
         "url":"http://www.korokithakis.net/tutorials/python/"} ]

    django_pages = [
        {"title":"Official Django Tutorial",
         "url":"https://docs.djangoproject.com/en/1.9/intro/tutorial01/"},
        {"title":"Django Rocks",
         "url":"http://www.djangorocks.com/"},
        {"title":"How to Tango with Django",
         "url":"http://www.tangowithdjango.com/"}]

    other_pages = [
        {"title":"Bottle",
         "url":"http://bottlepy.org/docs/dev/"},
        {"title":"Flask",
         "url":"http://flask.pocoo.org"} ]

    cats = {"Python": {"pages": python_pages},
            "Django": {"pages": django_pages},
            "Other Frameworks": {"pages": other_pages} }

    for cat, cat_data in cats.items():
        c = add_cat(cat)
        for p in cat_data["pages"]:
            add_page(c, p["title"], p["url"])

    # Print out the categories we have added.
    for c in Category.objects.all():
        for p in Page.objects.filter(category=c):
            print("- {0} - {1}".format(str(c), str(p)))

def add_page(cat, title, url, views=0):
    p = Page.objects.get_or_create(category=cat, title=title)[0]
    p.url=url
    p.views=views
    p.save()
    return p

def add_cat(name):
    c = Category.objects.get_or_create(name=name)[0]
    c.save()
    return c

# Start execution here!
if __name__ == '__main__':
    print("Starting Rango population script...")
    populate()

tango_with_django_project/rango/admin.py文件内容如下

from django.contrib import admin
from rango.models import Category, Page

admin.site.register(Category)
admin.site.register(Page)

tango_with_django_project/rango/models.py文件内容如下

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=128, unique=True)

    class Meta:
        verbose_name_plural = 'Categories'

    def __str__(self):
        return self.name


class Page(models.Model):
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=128)
    url = models.URLField()
    views = models.IntegerField(default=0)

    def __str__(self):
        return self.title

tango_with_django_project/rango/urls.py文件内容如下

from django.conf.urls import url
from rango import views

urlpatterns=[
    url(r'^$',views.index,name='index'),
    url(r'^about/', views.about, name='about')
]

tango_with_django_project/rango/views.py文件内容如下

from django.shortcuts import render

def index(request):
    context_dict={'boldmessage': "Crunchy, creamy, cookie, candy, cupcake!"}
    return render(request,'rango/index.html',context=context_dict)


def about(request):
    myContext="Hello World!"
    return render(request,'rango/about.html',{'myContext':myContext})

index页面

这里写图片描述

about页面

这里写图片描述

admin页面

这里写图片描述

这里写图片描述

这里写图片描述

5.Models and Databases——Exercises

Now that you’ve completed this chapter, try out these exercises to reinforce and practice what you have learnt. Once again, note that the following chapters will have expected you to have completed these exercises! If you’re stuck, there are some hints to help you complete the exercises below.

  • Update the Category model to include the additional attributes views
    and likes where the default values for each are both zero (0).

这里写图片描述

  • Make the migrations for your app and then migrate your database to
    commit the changes.

这里写图片描述
- Update your population script so that the Python category has 128
views and 64 likes, the Django category has 64 views and 32 likes,
这里写图片描述

  • Delete and recreate your database, populating it with your updated
    population script.

这里写图片描述

这里写图片描述

  • Complete parts two and seven of the official Django tutorial. These
    sections will reinforce what you’ve learnt on handling databases in
    Django, and show you additional techniques to customising the Django
    admin interface.
  • Customise the admin interface. Change it in such a way so that when
    you view the Page model, the table displays the category, the name of
    the page and the url - just like in the screenshot shown below. You
    will need to complete the previous exercises or at least go through
    the official Django Tutorial to complete this exercise.

这里写图片描述

这里写图片描述

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值