用Django搭建个人博客—(3)

今日主题

  • 定义博客文章和评论的的数据库定义

  • 定义操作这几个Model的后台数据

User表

USER_STATUS = (
    ('active', u'激活'),
    ('suspended', u'禁用'),
    ('deleted', u'注销'),
)
class Users(models.Model):
    username = models.CharField(u'用户名', unique=True, max_length=20)
    password = models.CharField(u'密码', max_length=128)
    nickname = models.CharField(u'昵称', max_length=50, blank=True)
    avatar = models.ImageField(u'头像', upload_to='avatar/%Y/%m', max_length=100, blank=True, null=True)
    display = models.CharField(u'显示名', max_length=100, blank=True)
    email = models.EmailField(u'邮箱', max_length=255, blank=True)
    url = models.URLField(u'个人主页', max_length=255, blank=True)
    created_at = models.DateTimeField(u'创建时间', auto_now_add=True)
    activation_key = models.CharField(u'激活码', max_length=60, blank=True)
    status = models.CharField(u'状态', max_length=10, default='active', choices=USER_STATUS)

这里简单说明一点点,Django里面很少用到纯粹的sql.基本上都是用Django封装的orm来干这些事情.
SQL里面的数据字段的类型在Django里面也一一对应了的,上面的User模型定义里面的CharField,IntegerField,DateTimeField等分别对应了SQL里面的字符型,整型和日期型的数据格式,
EmailField,URLField等则是Django扩展出来的字段,实际上也相当于char型的字段(多了些特定的限制而已)

扩展阅读

Model field

这一部分应该来说是比较基础也比较重要的,务必应当熟悉各个字段的使用以及相应的属性.
当然,如果有SQL基础,那更是驾轻就熟.

这里还有一点需要提醒注意的是,avatar字段使用了ImageField,并且在其属性中给定了upload_to字段.那么我们在settings.py中就需要额外的为之设定一个图片存储路径.这样图片在上传的时候就会从
settings查找MEDIA_ROOT,并将图片至于其中, 可能细心的你还注意到了在设定upload_to字段的值上面
avatar/%Y/%m 这样最终生成的图片路径就应该是这样的 /path/to/upload/avatar/2015/01/xx.jpg
(假设选定了一张名为xx.jpg作为头像上传了).

# settings.py
# 设定图片上传路径
MEDIA_ROOT = os.path.join(BASE_DIR, 'upload')
if not os.path.exists(MEDIA_ROOT):
    os.mkdir(MEDIA_ROOT)

Posts表

def _make_uuid():
    return str(uuid.uuid4()).replace('-', '').lower()

POST_STATUS = (
    ('publish', u'发布'),
    ('auto-draft', u'草稿'),
    ('inherit', u'继承'),
)
COMMENT_STATUS = (
    ('open', u'公开'),
    ('closed', u'私密'),
)
class Posts(models.Model):
    title = models.CharField(u'标题', max_length=200)
    seed = models.CharField(max_length=40, default=_make_uuid)
    author = models.ForeignKey('Users', to_field='username')
    name = models.SlugField(u'别名', max_length=200, blank=True)
    date = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    excerpt = models.TextField(u'摘要')
    content = models.TextField(u'正文')
    status = models.CharField(u'发布状态', max_length=20, default='publish', choices=POST_STATUS)
    comment_status = models.CharField(u'评论状态', max_length=20, default='open', choices=COMMENT_STATUS)
    password = models.CharField(u'密码', max_length=20, blank=True)
    comment_count = models.IntegerField(u'评论', max_length=20, default=0)
    read_count = models.IntegerField(u'阅读', max_length=20, default=0)

Posts表用来存储博客的文章,心情随笔等等.所以像标题 内容 发布时间 修改时间等等的都是必不可少的

Comments表

class Comments(models.Model):
    post = models.ForeignKey('Posts')
    parent = models.ForeignKey('self', blank=True, null=True)
    author = models.ForeignKey('Users')
    author_name = models.CharField(max_length=20, blank=True)
    author_email = models.CharField(max_length=255, blank=True)
    author_url = models.URLField(max_length=255, blank=True)
    author_IP = models.GenericIPAddressField(unpack_ipv4=True, blank=True, null=True)
    date = models.DateTimeField(auto_now_add=True)
    content = models.TextField()

Links表

LINK_VISIBLE = (
    ('Y', u'可见'),
    ('N', u'不可见'),
)
class links(models.Model):
    owner = models.ForeignKey('users')
    url = models.URLField(max_length=255)
    name = models.CharField(max_length=255)
    image = models.CharField(max_length=255, blank=True)
    target = models.CharField(max_length=25, blank=True)
    description = models.CharField(max_length=255, blank=True)
    visible = models.CharField(max_length=20, default='Y', choices=LINK_VISIBLE)
    date = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    rating = models.IntegerField(default=0)

这些天有些冷,人都变得倦怠了.应该自我检讨一下了.

附带一笔记录一下今天使用Django form的一点笔记:

此处以Users为例,小叙一下通过Django自定义的表单进行数据验证

# 1
from django.forms import forms

class UserForm(forms.ModelForm):
    class Meta:
        model = models.Users
        fields = ['username', 'password']

最简单的一个Form就这么华丽丽的完成了,
models.Users 指定模型
fields 指定必要字段
然后在后台的views中就可以直接调用这个写好的Form对数据进行验证了,当然,同样也可以利用它生成表格输入框

进一步深入, 自定义字段验证

# 1
from django.forms import forms

class UserForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        # 为什么没有**kwargs, 是不是去读读源码?
        super(UserForm, self).__init__(*args)
        # do something with sth in kwargs

    def clean(self):
        # 让自带的方法帮我们验证剩余的字段
        cleaned_data = super(UserForm, self).clean()

        username = cleaned_data.get('username')
        if 'ooxx' in username:
            self._errors['username'] = u'名字太黄了,禁止注册!'
            del cleaned_data['username']

        pwd = cleaned_data.get('password')
        if len(str(pwd)) < 4:
            self._errors['password'] = u'那啥太短了,密码太短了.'
            del cleaned_data['password']

        # ....

        return cleaned_data

    class Meta:
        model = models.Users
        fields = ['username', 'password', 'email']

再简单的写一个后台的用户注册和编辑的views

# users.py
from django.shortcuts import RequestContext
from django.shortcuts import render_to_response

from blog import models
from blog import forms

def add(request, *args, **kwargs):
    if request.method == 'POST':
        form = forms.UserForm(request.POST)
        if form.is_valid():
            user = form.save()
            return render_to_response('core/user.html', {'user': user}, context_instance=RequestContext(request))
        else:
            return render_to_response('core/register.html', {'form': form}, context_instance=RequestContext(request))
    form = forms.UserForm()
    return render_to_response('core/register.html', {'form': form}, context_instance=RequestContext(request))

def edit(request, *args, **kwargs):
    username = request.POST.get('username', None)
    if username:
        obj = models.Users.objects.get(username=username)
        form = forms.UserForm(request.POST, instance=obj)
        if form.is_valid():
            form.save()
            return render_to_response('core/user.html', {'user': user}, context_instance=RequestContext(request))
        return render_to_response('core/edit.html', {'form': form}, context_instance=RequestContext(request))
posted @ 2015-01-26 22:21  Mx.Hu  阅读(547)  评论(0编辑  收藏  举报