1.首先创建一个工程newsns
django-admin.py startproject newsns
在工程目录下新建一个文件夹templates,在settings.py文件中对该模版路径进行配置:
1 import os 2 3 ROOT_DIR = os.getcwd() 4 5 6 TEMPLATE_DIRS = ( 7 # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". 8 # Always use forward slashes, even on Windows. 9 # Don't forget to use absolute paths, not relative paths.10 ROOT_DIR + '/templates/',11 )
然后在templates文件夹下创建一个模版index.html:
newsns -by django Django, my first django program.
参照上篇文章中创建模版的方法,将app目录下的settings.py文件、views.py文件和urls.py文件进行相应设置。
2.创建数据库,配置数据
在app目录下的settings.py中进行如下设置
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'newsns', # Or path to database file if using sqlite3. 'USER': 'root', # Not used with sqlite3. 'PASSWORD': '***', #密码. 'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. }}
增加app newsns:
1 INSTALLED_APPS = ( 2 'django.contrib.auth', 3 'django.contrib.contenttypes', 4 'django.contrib.sessions', 5 'django.contrib.sites', 6 'django.contrib.messages', 7 'django.contrib.staticfiles', 8 # Uncomment the next line to enable the admin: 9 # 'django.contrib.admin',10 # Uncomment the next line to enable admin documentation:11 # 'django.contrib.admindocs',12 'newsns',13 )
在控制台中使用mysql命令创建数据库newsns
mysql> create database newsns default character set utf8 collate utf8_general_ci;Query OK, 1 row affected (0.03 sec)
然后在app目录下创建一个models.py文件,该文件创建了3个类,实际上每个类代表一个表格,类的字段为表的字段。
1 #coding:utf-8 2 3 from django.db import models 4 5 class newsns(models.Model): 6 name = models.CharField(max_length = 30) 7 content = models.CharField(max_length = 140) 8 9 #以下代码可以不要10 class Publisher(models.Model):11 name = models.CharField(max_length=30)12 address = models.CharField(max_length=50)13 city = models.CharField(max_length=60)14 state_province = models.CharField(max_length=30)15 country = models.CharField(max_length=50)16 website = models.URLField()17 18 class Author(models.Model):19 first_name = models.CharField(max_length=30)20 last_name = models.CharField(max_length=40)21 email = models.EmailField()22 23 class Book(models.Model):24 title = models.CharField(max_length=100)25 authors = models.ManyToManyField(Author)26 publisher = models.ForeignKey(Publisher)27 publication_date = models.DateField()
在控制台输入以下命令,按照要求输入帐号、密码,建立上述表格:
***@Android:~/newsns# python manage.py validate0 errors found***@Android:~/newsns# python manage.py syncdb
创建好表格后我们在manage.py shell中进行测试:
1 ***@Android:~/newsns# python manage.py shell 2 Python 2.7.3 (default, Aug 1 2012, 05:14:39) 3 Type "copyright", "credits" or "license" for more information. 4 5 IPython 0.13.1 -- An enhanced Interactive Python. 6 ? -> Introduction and overview of IPython's features. 7 %quickref -> Quick reference. 8 help -> Python's own help system. 9 object? -> Details about 'object', use 'object??' for extra details.10 11 In [1]: from newsns.models import Publisher12 13 In [2]: p = Publisher(name = 'Jim', city = 'beijing')14 15 In [3]: p.save()16 17 In [4]: l = Publisher.objects.all()18 19 In [5]: for n in l:20 ...: print n.name21 ...: 22 Jim
好了,测试无误。
3.创建表单
在app目录下创建forms.py文件,内容和models.py呼应。
1 #coding:utf-82 3 from django import forms4 5 class snsform(forms.Form):6 name = forms.CharField(label = "姓名")7 content = forms.CharField(label = "内容", widget = forms.Textarea)
在views.py中添加下述代码:
1 def home(request): 2 if request.method == 'POST': 3 data = newsns() 4 for i in request.POST.keys(): 5 if hasattr(data, i): 6 setattr(data, i, request.POST[i]) 7 data.save() 8 f = snsform() 9 ls = newsns.objects.all()10 return render_to_response("home.html", { "ls":ls, "f":f}, context_instance = RequestContext(request))
注意要添加引入模块
#coding:utf-8from django.http import HttpResponsefrom django.template import Template, Contextfrom django.shortcuts import render_to_response, redirectfrom mysns.models import newsnsfrom django.template import RequestContextfrom mysns.forms import snsform
在templates目录下创建default文件夹,在该文件夹下建立一个layout.html文件,添加如下代码:
1 2 34748 {% block content %}49 {% endblock %}50
然后再创建一个home.html文件,添加代码
{% extends 'default/layout.html' %}{% block content %}
{%for i in ls%}
layout.html文件中的
{% block content %}{% endblock %}
表示home.html中{% block content %}与{% endblock %}之间的代码。
接下来在urls.py文件中添加url匹配
(r'^home', home),
注意要导入home函数。
我们还需要在views.py文件中实现编辑和删除功能。
编辑功能的实现思路是:获取需要编辑的帖子的id,根据该id从数据库中读取内容,在编辑页面edit.html中显示,让用户对内容进行修改,用户修改后进行post提交,根据id保存至数据库,id为原来的id,即id = int(request.GET['id'])。
删除功能的实现思路是:读取需要删除的帖子的id,根据该id从数据库中读取内容,将其删除。具体实现代码为:
1 def delete(request): 2 if 'id' in request.GET: 3 id = int(request.GET['id']) 4 delcontent = newsns.objects.get(id = id) 5 delcontent.delete() 6 return redirect('/home') 7 8 def edit(request): 9 if request.method == 'GET':10 if 'id' in request.GET:11 ls = newsns.objects.get(id = int(request.GET['id']))12 f = snsform(data = { 'name':ls.name, 'content':ls.content})13 return render_to_response("edit.html", { "f":f}, context_instance = RequestContext(request))14 if request.method == 'POST':15 data = newsns.objects.get(id = int(request.GET['id']))16 for i in request.POST.keys():17 if hasattr(data, i):18 setattr(data, i, request.POST[i])19 data.save()
现在我们还需要在模版目录下创建edit.html文件:
1 {%extends 'default/layout.html' %} 2 {% block content %} 310 11
12 {%for i in ls%}13
浏览器中输入,打开便是一个具备基本增删改查功能的sns了。