官网上的tutorial就不说了,这个肯定是要先看的。
下面以一个创建用户的例子来说明model, form和view的使用。注意这里不是用自动的admin功能。而是手动写MVC来添加用户。
首先要创建一个project. 我是在WINDOWS上做的,所以都有python命令,LINUX可以忽略这个。
python django-admin.py startproject mysite
创建一个app。
python manage.py startapp usermgmt
然后是创建model。
在mysite/usermgmt下创建一个文件models.py
class User(models.Model):
## Fields
username = models.CharField(max_length = 32, verbose_name = u'用户名');
password = models.CharField(max_length = 20, verbose_name = u'密码');
gender = models.IntegerField(choices = GENDER, verbose_name = u'性别');
mobilePhone = models.CharField(max_length = 11, verbose_name = u'手机号码');
telephone = models.CharField(max_length = 8, verbose_name = '电话号码');
city = models.IntegerField(choices = CITIES, verbose_name = '所在城市');
email = models.EmailField(unique = True, verbose_name = 'Email');
msn = models.EmailField(verbose_name = 'MSN');
qq = models.IntegerField(verbose_name = 'QQ');
registerTime = models.DateField(verbose_name = u'注册时间');
verify = models.ForeignKey(Verify, verbose_name = u'验证码'); ## foreign key
isActivated = models.BooleanField(verbose_name = u'是否激活');
isLocked = models.BooleanField(verbose_name = u'是否被锁定');
lastLoginTime = models.DateTimeField(verbose_name = u'上次登录时间');
lastLoginIP = models.IPAddressField(verbose_name = u'上次登录IP');
totalLoginCount = models.IntegerField(default = 0, verbose_name = u'总计登录次数');
totalPostCount = models.IntegerField(default = 0, verbose_name = u'总计发布信息数');
reportedCount = models.IntegerField(default = 0, verbose_name = u'总计被举报数');
## Methods
def __unicode__(self):
return self.username;
def get_absolute_url(self):
return "/userapi/%i/" % self.id;
有了model,就要创建对应的form。其实这不是必须,不过既然django提供了对form的简化处理,就该好好利用。
同样在mysite/usermgmt下创建一个文件forms.py
from django.db import models;
from django.forms import ModelForm;
class UserForm(ModelForm):
class Meta:
model = User;
exclude = ('registerTime', 'isActivated', 'isLocked', 'lastLoginTime', 'lastLoginIP',
'totalLoginCount', 'totalPostCount', 'reportedCount');
exclude值表示这些字段在页面呈现的时候并不显示。注意,页面中也不会出现这些字段的隐藏字段。
然后我们就可以创建对应的view处理程序了。
在mysite/usermgmt下创建一个文件views.py
from django.http import HttpResponse;
from django.forms import ModelForm;
from django.shortcuts import render_to_response;
from usermgmt.models import *;
from usermgmt.forms import *;
def newuser(request):
form = None;
if request.POST:
user = User();
form = UserForm(request.POST, instance = user);
if form.is_valid():
form.save();
return render_to_response('usermgmt/newuser.html',
{
'form': form,
'msg': 'User added successfully!',
});
else:
form = UserForm();
return render_to_response('usermgmt/newuser.html', {'form': form,});
MVC都全了么?没,还有newuser.html,这个页面模板。
在mysite下创建一个文件夹叫 templates,然后在里面创建一个文件夹叫usermgmt。因为一个django的project是可以包含多个app的,所以给不同的app建立不同的文件夹是比较好的选择。然后在里面创建一个newuser.html。内容极其简单。
<html>
<head>
<title>User register</title>
</head>
<body>
<form method="post" action="">
<table>
{{ form }}
</table>
<input type="submit" value="Submit"/>
<div>{{ msg }}</div>
</form>
</body>
</html>
现在万事俱备,就剩改一些settings了。
因为我们添加了一个新的app,所以在mysite/urls.py中需要修改成:
from django.conf.urls.defaults import *
from django.contrib import admin;
admin.autodiscover();
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('HouseRentPrj.HouseRent.views',
# Example:
# (r'^HouseRentPrj/', include('HouseRentPrj.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^HouseRent/', include('mysite.usermgmt.urls')),
(r'^admin/', include(admin.site.urls)),
)
在settings.py中,INSTALLED_APPS中要加上mysite.usermgmt.
TEMPLATE_DIRS加上刚才的模板路径,注意这里必须是绝对路径。
上面这些修改相当于添加了这个app。
而URL映射是要在具体的app的urls.py中来修改的。
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('HouseRentPrj.HouseRent.views',
# Example:
# (r'^helloworld/', include('helloworld.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^newuser/$', 'newuser'),
)
这样就好了,python manage.py runserver
然后在浏览器中输入 http://127.0.0.1:8000/mysite/newuser/试试。