用django创建一个简单的sns

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:

<title>newsns -by django</title>

<h1><font color=#{{color}}>Django, my first django program.</font></h1>

参照上篇文章中创建模版的方法,将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 validate

0 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 Publisher

12 

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.name

21    ...:     

22 Jim

好了,测试无误。

3.创建表单

在app目录下创建forms.py文件,内容和models.py呼应。

1 #coding:utf-8

2 

3 from django import forms

4 

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-8

from django.http import HttpResponse

from django.template import Template, Context

from django.shortcuts import render_to_response, redirect

from mysns.models import newsns

from django.template import RequestContext

from mysns.forms import snsform

在templates目录下创建default文件夹,在该文件夹下建立一个layout.html文件,添加如下代码:

 1 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

 2 <link rel="stylesheet" type="text/css" href="/static/bootstrap/css/bootstrap.min.css">

 3 <div class="navbar navbar-fixed-top">

 4   <div class="navbar-inner">

 5     <div class="container-fluid">

 6       <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

 7         <span class="icon-bar"></span>

 8         <span class="icon-bar"></span>

 9         <span class="icon-bar"></span>

10       </a>

11       <a class="brand" href="#">Uliweb Zone</a>

12       <div class="nav-collapse">

13 

14 <ul class="nav">

15 

16 <li><a href="/"><span>首页</span></a></li><li><a href="/forum"><span>论坛</span></a></li><li class="active"><a href="/tutorial"><span>教程</span></a></li><li><a href="/about"><span>关于</span></a></li>

17 

18 

19 

20 </ul>

21 

22 

23 <style>

24 #userinfo.btn-toolbar {margin-top:0;margin-bottom:0;font-size:14px;}

25 #userinfo.btn-toolbar a{vertical-align:middle;}

26 #userinfo img {

27 -webkit-border-radius: 3px;

28    -moz-border-radius: 3px;

29         border-radius: 3px;

30 }

31 #userinfo [class^="icon-"], #userinfo [class*=" icon-"], #userinfo [class^="icon-"]:hover, #userinfo [class*=" icon-"]:hover{

32     vertical-align:middle;

33     margin-bottom:3px;

34 }

35 </style>

36 

37 

38         <p class="pull-right user_info">

39             <a href="/login">登录</a> | <a href="/register">注册</a>

40         </p>

41 

42 

43       </div><!--/.nav-collapse -->

44     </div>

45   </div>

46 </div>

47 <div style= 'padding:50px 5px 15px 20px;'>

48 {% block content %}

49 {% endblock %}

50 </div>

然后再创建一个home.html文件,添加代码

{% extends 'default/layout.html' %}

{% block content %}

<form action = "" method = "post">

        {% csrf_token %}

        <table>

                {{f}}

        </table>

        <input type="submit" value="发送" class = 'btn btn-info'>

</form>



<hr>

{%for i in ls%}

<li>{{i.content}}<a class='btn' href = '/delete?id={{i.id}}'>删除</a><a class = 'btn' href = '/edit?id={{i.id}}'>编辑</a></li>

{%endfor%}

</hr>



{% endblock %}

 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 %}

 3 <form action = "" method = "post">

 4         {% csrf_token %}

 5         <table>

 6                 {{f}}

 7         </table>

 8         <input type="submit" value="发送" class = 'btn btn-info'>

 9 </form>

10 

11 <hr>

12 {%for i in ls%}

13 <li>{{i.content}}

14 {%endfor%}

15 </hr>

16 

17 {% endblock %}

浏览器中输入http://127.0.0.1:8000/home,打开便是一个具备基本增删改查功能的sns了。

用django创建一个简单的sns

 

 

你可能感兴趣的:(django)