基于How To Tango With Django 1.9的重新实践(0-5)
来源:互联网 发布:seo与sem的异同 编辑:程序博客网 时间:2024/05/17 08:17
我使用的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 = TrueALLOWED_HOSTS = []# Application definitionINSTALLED_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/#databasesDATABASES = { '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-validatorsAUTH_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 = TrueUSE_L10N = TrueUSE_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,includefrom django.contrib import adminfrom django.conf import settingsfrom django.conf.urls.static import staticurlpatterns = [ 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 osos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings')import djangodjango.setup()from rango.models import Category, Pagedef 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 pdef 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 adminfrom rango.models import Category, Pageadmin.site.register(Category)admin.site.register(Page)
tango_with_django_project/rango/models.py
文件内容如下
from django.db import modelsclass Category(models.Model): name = models.CharField(max_length=128, unique=True) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.nameclass 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 urlfrom rango import viewsurlpatterns=[ url(r'^$',views.index,name='index'), url(r'^about/', views.about, name='about')]
tango_with_django_project/rango/views.py
文件内容如下
from django.shortcuts import renderdef 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.
- 基于How To Tango With Django 1.9的重新实践(0-5)
- 基于How To Tango With Django 1.9的重新实践(7)——Forms
- 基于How To Tango With Django 1.9的重新实践(8)——Templates
- 基于How To Tango With Django 1.9的重新实践(9)——User Authentication
- 基于How To Tango With Django 1.9的重新实践(12)——Bootstrapping Rango
- 基于How To Tango With Django 1.9的重新实践(13)——Template Tags
- 基于How To Tango With Django 1.9的重新实践(14)——Bing Search
- 基于How To Tango With Django 1.9的重新实践(15)——Webhose Search
- 基于How To Tango With Django 1.9的重新实践(16)——Rango Exercises
- 基于How To Tango With Django 1.9的重新实践(17)——Hints
- 基于How To Tango With Django 1.9的重新实践(18)——JQuery
- 基于How To Tango With Django 1.9的重新实践(19)——Ajax
- 基于How To Tango With Django 1.9的重新实践(11)——User Authentication with {#chapter-redux}
- 基于How To Tango With Django 1.9的重新实践(6)——Models, Templates and Views
- 基于How To Tango With Django 1.9的重新实践(10)——Cookies and Sessions
- 基于How To Tango With Django 1.7的实践(5)——Models and Databases
- 基于How To Tango With Django 1.7的实践(3)——Django Basics
- 基于How To Tango With Django 1.7的实践(1)
- 1.4.2冒泡法(先排序再去重)
- 链表菜单之初级版
- DeepMind组建美国团队:加强与谷歌的联系
- FZU 1036 四塔问题(规律)
- leetcode144. Binary Tree Preorder Traversal
- 基于How To Tango With Django 1.9的重新实践(0-5)
- HDU3488-Tour
- 归并排序实现及时间复杂度分析
- [BZOJ 1005][HNOI2008]明明的烦恼(prufer编码+组合数学+高精度)
- 【BZOJ1076】【SCOI2008】奖励关(期望+状压dp)
- 盾神与条状项链
- android:versionCode和android:versionName
- Thymeleaf初探
- 关于不能创业失败