Django續

Formcss

django中的Form通常有兩種功能:html

  • 輸入html
  • 驗證用戶輸入
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re
from django import forms
from django.core.exceptions import ValidationError


def mobile_validate(value):
    mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')
    if not mobile_re.match(value):
        raise ValidationError('手機號碼格式錯誤')


class PublishForm(forms.Form):

    user_type_choice = (
        (0, u'普通用戶'),
        (1, u'高級用戶'),
    )

    user_type = forms.IntegerField(widget=forms.widgets.Select(choices=user_type_choice,
                                                                  attrs={'class': "form-control"}))

    title = forms.CharField(max_length=20,
                            min_length=5,
                            error_messages={'required': u'標題不能爲空',
                                            'min_length': u'標題最少爲5個字符',
                                            'max_length': u'標題最多爲20個字符'},
                            widget=forms.TextInput(attrs={'class': "form-control",
                                                          'placeholder': u'標題5-20個字符'}))

    memo = forms.CharField(required=False,
                           max_length=256,
                           widget=forms.widgets.Textarea(attrs={'class': "form-control no-radius", 'placeholder': u'詳細描述', 'rows': 3}))

    phone = forms.CharField(validators=[mobile_validate, ],
                            error_messages={'required': u'手機不能爲空'},
                            widget=forms.TextInput(attrs={'class': "form-control",
                                                          'placeholder': u'手機號碼'}))

    email = forms.EmailField(required=False,
                            error_messages={'required': u'郵箱不能爲空','invalid': u'郵箱格式錯誤'},
                            widget=forms.TextInput(attrs={'class': "form-control", 'placeholder': u'郵箱'}))
def publish(request):
    ret = {'status': False, 'data': '', 'error': '', 'summary': ''}
    if request.method == 'POST':
        request_form = PublishForm(request.POST)
        if request_form.is_valid():
            request_dict = request_form.clean()
            print request_dict
            ret['status'] = True
        else:
            error_msg = request_form.errors.as_json()
            ret['error'] = json.loads(error_msg)
    return HttpResponse(json.dumps(ret))

擴展:ModelFormpython

在使用Model和Form時,都須要對字段進行定義並指定類型,經過ModelForm則能夠省去From中字段的定義sql

class AdminModelForm(forms.ModelForm):
      
    class Meta:
        model = models.Admin
        #fields = '__all__'
        fields = ('username', 'email')
          
        widgets = {
            'email' : forms.PasswordInput(attrs={'class':"alex"}),
        }

經常使用ORM操做:數據庫

from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField()

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()
    authors = models.ManyToManyField(Author)
    n_comments = models.IntegerField()
    n_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    def __str__(self):              # __unicode__ on Python 2
        return self.headline
View Code

建立django

>>> from blog.models import Blog
>>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
>>> b.save()

這是在後臺執行INSERT SQL操做。只有當Django執行了save()語句纔會將執行的操做添加到數據庫中。固然save()語句並無返回值。json

處理帶外鍵關聯或多對多關聯的對象 

外鍵的關聯:網絡

>>> from blog.models import Entry
>>> entry = Entry.objects.get(pk=1)
>>> cheese_blog = Blog.objects.get(name="Cheddar Talk")
>>> entry.blog = cheese_blog
>>> entry.save()

多對多關聯:app

>>> from blog.models import Author
>>> joe = Author.objects.create(name="Joe")
>>> entry.authors.add(joe)

添加多個多對多的對象ide

>>> john = Author.objects.create(name="John")
>>> paul = Author.objects.create(name="Paul")
>>> george = Author.objects.create(name="George")
>>> ringo = Author.objects.create(name="Ringo")
>>> entry.authors.add(john, paul, george, ringo)

查詢

all_entries = Entry.objects.all() #查詢全部
Entry.objects.filter(pub_date__year=2006) #查詢全部pub_date爲2006年的紀錄
Entry.objects.all().filter(pub_date__year=2006) #與上面那句同樣
>>> Entry.objects.filter(   #鏈式查詢
...     headline__startswith='What'
... ).exclude(
...     pub_date__gte=datetime.date.today()
... ).filter(
...     pub_date__gte=datetime(2005, 1, 30)
... )

one_entry = Entry.objects.get(pk=1) #單條查詢

Entry.objects.all()[:5] #查詢前5條
Entry.objects.all()[5:10] #你猜

Entry.objects.order_by('headline')[0] #按headline排序取第一條

Entry.objects.filter(pub_date__lte='2006-01-01') #至關於sql語句SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';

Entry.objects.get(headline__exact="Cat bites dog") #至關於SELECT ... WHERE headline = 'Cat bites dog';
Blog.objects.get(name__iexact="beatles blog") #與上面相同,只是大小寫不敏感

Entry.objects.get(headline__contains='Lennon') #至關 於SELECT ... WHERE headline LIKE '%Lennon%';
單表內查詢語句
#This example retrieves all Entry objects with a Blog whose name is 'Beatles Blog':
Entry.objects.filter(blog__name='Beatles Blog')

Blog.objects.filter(entry__headline__contains='Lennon')
關聯查詢

Admin

django amdin是django提供的一個後臺管理頁面,給管理頁面提供完善的html和css,使得你在經過Model建立完數據庫表以後,就能夠對數據進行增刪改查,而使用django admin 則須要如下步驟:

  • 建立後臺管理員
  • 配置url
  • 註冊和配置django admin後臺管理頁面

一、建立後臺管理員

>> python manage.py createsuperuser

二、配置後臺管理url

>> url(r'^admin/', include(admin.site.urls))

三、註冊和配置django admin 後臺管理頁面

a、在admin中執行以下配置

from django.contrib import admin
  
from app01 import  models
  
admin.site.register(models.UserType)
admin.site.register(models.UserInfo)
admin.site.register(models.UserGroup)
admin.site.register(models.Asset)

b、設置數據表名稱

class UserType(models.Model):
    name = models.CharField(max_length=50)
  
    class Meta:
        verbose_name = '用戶類型'
        verbose_name_plural = '用戶類型'

c、打開表以後,設定默認顯示,須要在model中做以下配置

class UserType(models.Model):
    name = models.CharField(max_length=50)
  
    def __unicode__(self):
        return self.name
from django.contrib import admin
  
from app01 import  models
  
class UserInfoAdmin(admin.ModelAdmin):
    list_display = ('username', 'password', 'email')
  
  
admin.site.register(models.UserType)
admin.site.register(models.UserInfo,UserInfoAdmin)
admin.site.register(models.UserGroup)
admin.site.register(models.Asset)

d、爲數據表添加搜索功能

from django.contrib import admin
  
from app01 import  models
  
class UserInfoAdmin(admin.ModelAdmin):
    list_display = ('username', 'password', 'email')
    search_fields = ('username', 'email')//添加搜索功能
  
admin.site.register(models.UserType)
admin.site.register(models.UserInfo,UserInfoAdmin)
admin.site.register(models.UserGroup)
admin.site.register(models.Asset)

e、添加快速過濾

from django.contrib import admin
  
from app01 import  models
  
class UserInfoAdmin(admin.ModelAdmin):
    list_display = ('username', 'password', 'email')
    search_fields = ('username', 'email')
    list_filter = ('username', 'email')//添加快速過濾功能
      
  
admin.site.register(models.UserType)
admin.site.register(models.UserInfo,UserInfoAdmin)
admin.site.register(models.UserGroup)
admin.site.register(models.Asset)

學員管理系統練習

項目需求:

1.分講師\學員\課程顧問角色,
2.學員能夠屬於多個班級,學員成績按課程分別統計
3.每一個班級至少包含一個或多個講師
4.一個學員要有狀態轉化的過程 ,好比未報名前,報名後,畢業老學員
5.客戶要有諮詢紀錄, 後續的按期跟蹤紀錄也要保存
6.每一個學員的全部上課出勤狀況\學習成績都要保存
7.學校能夠有分校區,默認每一個校區的員工只能查看和管理本身校區的學員
8.客戶諮詢要區分來源
#_*_coding:utf-8_*_
from django.db import models

# Create your models here.
from django.core.exceptions import ValidationError

from django.db import models
from django.contrib.auth.models import User

class_type_choices= (('online',u'網絡班'),
                     ('offline_weekend',u'面授班(週末)',),
                     ('offline_fulltime',u'面授班(脫產)',),
                     )
class UserProfile(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(u"姓名",max_length=32)
    def __unicode__(self):
        return self.name


class School(models.Model):
    name = models.CharField(u"校區名稱",max_length=64,unique=True)
    addr = models.CharField(u"地址",max_length=128)
    staffs = models.ManyToManyField('UserProfile',blank=True)
    def __unicode__(self):
        return self.name


class Course(models.Model):
    name = models.CharField(u"課程名稱",max_length=128,unique=True)
    price = models.IntegerField(u"面授價格")
    online_price = models.IntegerField(u"網絡班價格")
    brief = models.TextField(u"課程簡介")
    def __unicode__(self):
        return self.name


class ClassList(models.Model):
    course = models.ForeignKey('Course')
    course_type = models.CharField(u"課程類型",choices=class_type_choices,max_length=32)
    semester = models.IntegerField(u"學期")
    start_date = models.DateField(u"開班日期")
    graduate_date = models.DateField(u"結業日期",blank=True,null=True)
    teachers = models.ManyToManyField(UserProfile,verbose_name=u"講師")


    #def __unicode__(self):
    #    return "%s(%s)" %(self.course.name,self.course_type)

    class Meta:
        verbose_name = u'班級列表'
        verbose_name_plural = u"班級列表"
        unique_together = ("course","course_type","semester")


class Customer(models.Model):
    qq = models.CharField(u"QQ號",max_length=64,unique=True)
    name = models.CharField(u"姓名",max_length=32,blank=True,null=True)
    phone = models.BigIntegerField(u'手機號',blank=True,null=True)
    stu_id = models.CharField(u"學號",blank=True,null=True,max_length=64)
    #id = models.CharField(u"身份證號",blank=True,null=True,max_length=128)
    source_type = (('qq',u"qq羣"),
                   ('referral',u"內部轉介紹"),
                   ('51cto',u"51cto"),
                   ('agent',u"招生代理"),
                   ('others',u"其它"),
                   )
    source = models.CharField(u'客戶來源',max_length=64, choices=source_type,default='qq')
    referral_from = models.ForeignKey('self',verbose_name=u"轉介紹自學員",help_text=u"若此客戶是轉介紹自內部學員,請在此處選擇內部學員姓名",blank=True,null=True,related_name="internal_referral")

    course = models.ForeignKey(Course,verbose_name=u"諮詢課程")
    class_type = models.CharField(u"班級類型",max_length=64,choices=class_type_choices)
    customer_note = models.TextField(u"客戶諮詢內容詳情",help_text=u"客戶諮詢的大概狀況,客戶我的信息備註等...")
    status_choices = (('signed',u"已報名"),
                      ('unregistered',u"未報名"),
                      ('graduated',u"已畢業"),
                      )

    status = models.CharField(u"狀態",choices=status_choices,max_length=64,default=u"unregistered",help_text=u"選擇客戶此時的狀態")
    consultant = models.ForeignKey(UserProfile,verbose_name=u"課程顧問")
    date = models.DateField(u"諮詢日期",auto_now_add=True)

    class_list = models.ManyToManyField('ClassList',verbose_name=u"已報班級",blank=True)

    def __unicode__(self):
        return "%s,%s" %(self.qq,self.name )



class ConsultRecord(models.Model):
    customer = models.ForeignKey(Customer,verbose_name=u"所諮詢客戶")
    note = models.TextField(u"跟進內容...")
    status_choices = ((1,u"近期無報名計劃"),
                      (2,u"2個月內報名"),
                      (3,u"1個月內報名"),
                      (4,u"2周內報名"),
                      (5,u"1周內報名"),
                      (6,u"2天內報名"),
                      (7,u"已報名"),
                      )
    status = models.IntegerField(u"狀態",choices=status_choices,help_text=u"選擇客戶此時的狀態")

    consultant = models.ForeignKey(UserProfile,verbose_name=u"跟蹤人")
    date = models.DateField(u"跟進日期",auto_now_add=True)

    def __unicode__(self):
        return u"%s, %s" %(self.customer,self.status)

    class Meta:
        verbose_name = u'客戶諮詢跟進記錄'
        verbose_name_plural = u"客戶諮詢跟進記錄"



class CourseRecord(models.Model):
    course = models.ForeignKey(ClassList,verbose_name=u"班級(課程)")
    day_num = models.IntegerField(u"節次",help_text=u"此處填寫第幾節課或第幾天課程...,必須爲數字")
    date = models.DateField(auto_now_add=True,verbose_name=u"上課日期")
    teacher = models.ForeignKey(UserProfile,verbose_name=u"講師")
    def __unicode__(self):
        return u"%s 第%s天" %(self.course,self.day_num)
    class Meta:
        verbose_name = u'上課紀錄'
        verbose_name_plural = u"上課紀錄"
        unique_together = ('course','day_num')


class StudyRecord(models.Model):
    course_record = models.ForeignKey(CourseRecord, verbose_name=u"第幾天課程")
    student = models.ForeignKey(Customer,verbose_name=u"學員")
    record_choices = (('checked', u"已簽到"),
                      ('late',u"遲到"),
                      ('noshow',u"缺勤"),
                      ('leave_early',u"早退"),
                      )
    record = models.CharField(u"上課紀錄",choices=record_choices,default="checked",max_length=64)
    score_choices = ((100, 'A+'),
                     (90,'A'),
                     (85,'B+'),
                     (80,'B'),
                     (70,'B-'),
                     (60,'C+'),
                     (50,'C'),
                     (40,'C-'),
                     (0,'D'),
                     (-1,'N/A'),
                     (-100,'COPY'),
                     (-1000,'FAIL'),
                     )
    score = models.IntegerField(u"本節成績",choices=score_choices,default=-1)
    date = models.DateTimeField(auto_now_add=True)
    note = models.CharField(u"備註",max_length=255,blank=True,null=True)

    def __unicode__(self):
        return u"%s,學員:%s,紀錄:%s, 成績:%s" %(self.course_record,self.student.name,self.record,self.get_score_display())

    class Meta:
        verbose_name = u'學員學習紀錄'
        verbose_name_plural = u"學員學習紀錄"
        unique_together = ('course_record','student')
學員管理系統表結構
相關文章
相關標籤/搜索