Django 实例介绍

1. 创建工程

idea-create-project

Location: 项目路径

Application name: 应用名称

2. 项目目录视图

idea-project-structure

  • demosite 包含项目的文件夹
  • manage.py 命令工具,用于管理Django项目
  • 内嵌demosite python包
  • demosite/settings.py Django项目的配置文件
  • demosite/urls.py Django项目路由
  • demosite/wsgi.py Django项目部署配置
  • polls 应用路径
  • polls/admin.py Django后台管理配置
  • polls/models.py polls模型
  • polls/views.py polls视图
  • polls/tests.py polls测试
  • polls/apps.py polls入口
  • templates 模板文件夹

3. 配置数据库

文件 demosite/settings.py,如果链接其他数据库,需要修改ENGINE参数

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.demo.site'),
    }
}

4. 创建模型

编辑 polls/models.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models
# the following lines added:
import datetime
from django.utils import timezone


class Question(models.Model):
	question_text = models.CharField(max_length=200)
	pub_date = models.DateTimeField('date published')

	def __str__(self):
		return self.question_text

	def was_published_recently(self):
		now = timezone.now()
		return now - datetime.timedelta(days=1) <= self.pub_date <= now

	was_published_recently.admin_order_field = 'pub_date'
	was_published_recently.boolean = True
	was_published_recently.short_description = 'Published recently?'


class Choice(models.Model):
	question = models.ForeignKey(Question)
	choice_text = models.CharField(max_length=200)
	votes = models.IntegerField(default=0)

	def __str__(self):
		return self.choice_text

5. 创建数据库

执行命令:Tools-> Run Manage.py Task... 或者直接按快捷键:⌥R, 在弹出的命令窗口中执行声明模型变化命令:makemigrations polls
idea-makemigrations-polls

执行提交命令:sqlmigrate polls 0001

idea-sqlmigrate-polls

最后执行命令:migrate,在数据库中创建表

idea-migrate

6. 创建超级用户

在Run Manage.py Task...命令窗口执行命令:createsuperuser

idea-createsuperuser

在创建用户过程中,需要输入的信息有

  • UserName
  • Email address
  • Password
  • Password(again)

7. 配置管理端

编辑 polls/admin.py

from django.contrib import admin
from .models import Choice, Question


class ChoiceInline(admin.TabularInline):
	model = Choice
	extra = 3


class QuestionAdmin(admin.ModelAdmin):
	fieldsets = [
		(None, {'fields': ['question_text']}),
		('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
	]
	inlines = [ChoiceInline]


admin.site.register(Question, QuestionAdmin)

8. 编辑视图

编辑 polls/views.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse

from .models import Question, Choice


def index(request):
	latest_question_list = Question.objects.order_by('-pub_date')[:5]
	context = {'latest_question_list': latest_question_list}
	return render(request, 'polls/index.html', context)


def detail(request, question_id):
	question = get_object_or_404(Question, pk=question_id)
	return render(request, 'polls/detail.html', {'question': question})


def results(request, question_id):
	question = get_object_or_404(Question, pk=question_id)
	return render(request, 'polls/results.html', {'question': question})


def vote(request, question_id):
	question = get_object_or_404(Question, pk=question_id)
	try:
		selected_choice = question.choice_set.get(pk=request.POST['choice'])
	except (KeyError, Choice.DoesNotExist):
		return render(request, 'polls/detail.html', {
			'question': question,
			'error_message': "You didn't select a choice.",
		})
	else:
		selected_choice.votes += 1
		selected_choice.save()
		return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

9. 编辑路由

编辑文件 demosite/urls.py

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

urlpatterns = [
	url(r'^polls/', include('polls.urls')),  # this line added
	url(r'^admin/', admin.site.urls),
]

添加polls的路由文件 polls/urls.py

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

urlpatterns = [
	url(r'^$', views.index, name='index'),
	# ex: /polls/5/
	url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
	# ex: /polls/5/results/
	url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
	# ex: /polls/5/vote/
	url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]

10. 创建视图模板

在templates下创建文件夹polls,之后创建index.html、detail.html、results.html

编辑 index.html:

{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_question_list %}
           <ul>
    {% for question in latest_question_list %}
           <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
    {% endfor %}
       </ul>
{% else %}
           <p>No polls are available.</p>
{% endif %}

11. 使用样式

在polls包下创建文件夹:static/polls,之后创建样式文件style.css:

li a {
    color: green;
}

12. 测试

编辑 polls/tests.py

import datetime
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.utils import timezone
from .models import Question


def create_question(question_text, days):
	time = timezone.now() + datetime.timedelta(days=days)
	return Question.objects.create(question_text=question_text, pub_date=time)


class QuestionViewTests(TestCase):
	def test_index_view_with_no_questions(self):
		"""
		If no questions exist, an appropriate message should be displayed.
		"""
		response = self.client.get(reverse('index'))
		self.assertEqual(response.status_code, 200)
		self.assertContains(response, "No polls are available.")
		self.assertQuerysetEqual(response.context['latest_question_list'], [])

执行测试:

idea tests run

13. 运行

在程序运行过程中,python2.7可能会报ASCII编码错误,请在polls/apps.py 中添加:

from django.apps import AppConfig
import sys # new add

reload(sys) # new add
sys.setdefaultencoding('utf-8') # new add


class PollsConfig(AppConfig):
	name = 'polls'

原文:
https://www.jetbrains.com/help/pycharm/step-4-creating-and-running-your-first-django-project.html

原文地址:https://www.cnblogs.com/zhuhc/p/7806694.html