<commit_before>---
layout: post
title: Django
category: 技术
tags: Django
keywords: 
description: 
---


## 开发环境准备

```
#安装django
pip3 install -v django==1.10.7

#创建virtualenv
virtualenv django-env

#激活virtualenv
.\django-env\Scripts\activate.bat

#--------------------------------
#virtualenvwrapper神器

#virtualenv 的一个最大的缺点就是，每次开启虚拟环境之前要去虚拟环境所在目录下的 bin 
#目录下 source 一下 activate，这就需要我们记住每个虚拟环境所在的目录。一种可行的解决方案是，将所有的虚拟环境目录全都集中起来，
#比如放到 ~/virtualenvs/，并对不同的虚拟环境使用不同的目录来管理。virtualenvwrapper 正是这样做的。并且，它还省去了每次
#开启虚拟环境时候的 source 操作，使得虚拟环境更加好用。

#安装
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3
pip install virtualenvwrapper

#环境设定
export WORKON_HOME='~/.virtualenvs'
source /usr/local/bin/virtualenvwrapper.sh

#Create a new virtualenv in the WORKON_HOME directory
mkvirtualenv spider

#List all of the environments
lsvirtualenv

#show the content of the site-packages directory of the currently-active virtualenv.
lssitepackages

#List or change working virtual environments
workon spider

#退出虚拟环境
deactivate

#删除虚拟环境
rmvirtualenv spider

#--------------------------------
#创建新工程
django-admin.py startproject MyBlog

#创建app
python manage.py startapp article

#start web server
manage.py runserver

#同步生成DB 仅在第一次用
python manage.py migrate

#之后编辑model后，都要执行这两个
python manage.py makemigrations
python manage.py migrate

#创建超级用户
python manage.py createsuperuser

#python交互环境变量设置
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MyBlog.settings")
django.setup()

#settings

## database sqlite3 
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'MyBlog.db'),
    }
}

## Static files (CSS, JavaScript, Images)
  STATICFILES = os.path.join(BASE_DIR, 'static')

```

## Setting
- [LANGUAGE_CODE reference](http://www.i18nguy.com/unicode/language-identifiers.html) 
- [TIME_ZONE reference](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)
```
LANGUAGE_CODE = 'ja'
TIME_ZONE = 'Asia/Tokyo'

LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
```

## The view layer

### libs
```
#views lib
from django.shortcuts import render
from django.http import HttpResponse
from django.conf import settings

from django.views.generic import ListView,DetailView
django.views.generic
__all__ = [
    'View', 'TemplateView', 'RedirectView', 'ArchiveIndexView',
    'YearArchiveView', 'MonthArchiveView', 'WeekArchiveView', 'DayArchiveView',
    'TodayArchiveView', 'DateDetailView', 'DetailView', 'FormView',
    'CreateView', 'UpdateView', 'DeleteView', 'ListView', 'GenericViewError',
]

#常用成员变量和方法
-ListView
template_name
context_object_name
get_queryset

--分页
page_type
paginate_by
page_kwarg

-DetailView
template_name
model
pk_url_kwarg
context_object_name
get_object
get_context_data

-FormView
form_class
template_name
form_valid
form_invalid
get_context_data (第一次显示form和form_invalid时调用)


-RedirectView
get


#urls lib
from django.conf.urls import url,include

#forms lib
from django import forms
from django.forms import ModelForm
from django.forms import widgets

--django user
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import AuthenticationForm,UserCreationForm
from django.contrib.auth import login,logout
```

### FromView 继承基本调用方法
```



```
### urls
```
#eg.
url(r'^$', views.IndexView.as_view(), name='index')
url(r'^page/(?P<page>\d+)$', views.IndexView.as_view(), name='index_page'),
url(r'^article/(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/(?P<article_id>\d+).html$',
        views.ArticleDetailView.as_view(),
        name='detail'),
url(r'^category/(?P<category_name>\S+).html$',views.CategoryDetailView.as_view(),name='category_detail'

#regrex
(?P<year>\d+) group匹配

* 匹配前一个字符0次或无限次
+ 匹配前一个字符1次或无限次
? 匹配前一个字符0次或1次
\d 数字[0-9]
\s 空白字符
\S 非空白字符
\w 单词字符[A-Za-z0-9_]


```
### paginator
```
url(r'^page/(?P<page>\d+)$', views.IndexView.as_view(), name='index_page'),
context = {
                'paginator': paginator,
                'page_obj': page,
                'is_paginated': is_paginated,
                'object_list': queryset
}
```
### tags
```

#tag
from django import template
from django.template.defaultfilters import stringfilter
from django.conf import settings

register = template.Library()

@register.simple_tag
@register.inclusion_tag('blog/tags/breadcrumb.html')

@register.filter(is_safe=True)
@stringfilter

#将函数处理的结果赋值给一个变量
@register.assignment_tag

```

## The model layer
```
#lib
from django.db import models
from django.core.urlresolvers import reverse

#auth
AUTH_USER_MODEL='auth.User'

```


## The template layer

### 配置
```
#TEMPLATES
TEMPLATES 'DIRS': [os.path.join(BASE_DIR, 'templates')]
```

### 代码实例
```
#ModelForm实现例子
class CommentForm(ModelForm):
    url = forms.URLField(label='网址',required=False)
    email = forms.EmailField(label='电子邮箱', required=False)
    name = forms.CharField(label='姓名')
    parent_comment_id = forms.IntegerField(widget=forms.HiddenInput, required= False)


    class Meta:
        model = Comment
        fields = ['body']class CommentForm(ModelForm):
    url = forms.URLField(label='网址',required=False)
    email = forms.EmailField(label='电子邮箱', required=False)
    name = forms.CharField(label='姓名')
    parent_comment_id = forms.IntegerField(widget=forms.HiddenInput, required= False)


    class Meta:
        model = Comment
        fields = ['body']
        
#AuthenticationForm,UserCreationForm实现例子
class LoginForm(AuthenticationForm):
    def __init__(self,*args,**kwargs):
        super(LoginForm,self).__init__(*args,**kwargs)
        self.fields['username'].widget = widgets.TextInput(attrs={'placeholder':'username','class':'form-control'})
        self.fields['password'].widget = widgets.PasswordInput(attrs={'placeholder':'password','class':'form-control'})


class RegisterForm(UserCreationForm):
    def __init__(self,*args,**kwargs):
        super(RegisterForm,self).__init__(*args,**kwargs)

        self.fields['username'].widget = widgets.TextInput(attrs={'placeholder':'username','class':'form-control'})
        self.fields['email'].widget = widgets.EmailInput(attrs={'placeholder':'email','class':'form-control'})
        self.fields['password1'].widget = widgets.PasswordInput(attrs={'placeholder':'password','class':'form-control'})
        self.fields['password2'].widget = widgets.PasswordInput(attrs={'placeholder':'repeat password','class':'form-control'})

    class Meta:
        model = get_user_model()
        fields = ('username','email')
```
### formset
```
from django import forms
class ArticleForm(forms.Form): 
    title = forms.CharField()
    pub_date = forms.DateField()
    
from django.forms import formset_factory
ArticleFormSet = formset_factory(ArticleForm,extra=2)
formset = ArticleFormSet()
for form in formset:
    print(form.as_table())

# 表单内的errors,规则验证
formset.errors
#调单外的逻辑验证
formset.non_form_errors

```

### forms知识点
```
ManyToManyField Django 创建一个中间表来表示ManyToManyField关系。默认情况下，中间表的名称由两个关系表名结合而成。

new_blog=form.save(commit=False) 
new_blog.author=current_user 

##保存时，有两种方式
1.先通过new_blog.save() 保存blog数据，再通过form.save_m2m() manytomany关系到中间表
new_blog.save() 
form.save_m2m() 
2.此方法保存blog数据和保存manytomany关系到中间表
form.save()
```

## The admin layer
```
from django.contrib import admin
admin.site.register(Article)

```

## django部署
- [使用PythonAnyWhere和GitHub免费部署Django网站](https://segmentfault.com/a/1190000009240824)
- [如何在阿里云上部署 Django 应用程序](https://www.alibabacloud.com/zh/getting-started/projects/how-to-deploy-django-application-on-alibaba-cloud)

## ERRORS 
```<commit_msg>Update 2017-09-20-Django.md<commit_after>---
layout: post
title: Django
category: 技术
tags: Django
keywords: 
description: 
---


## 开发环境准备

```
#安装django
pip3 install -v django==1.10.7

#创建virtualenv
virtualenv django-env

#激活virtualenv
.\django-env\Scripts\activate.bat

#--------------------------------
#virtualenvwrapper神器

#virtualenv 的一个最大的缺点就是，每次开启虚拟环境之前要去虚拟环境所在目录下的 bin 
#目录下 source 一下 activate，这就需要我们记住每个虚拟环境所在的目录。一种可行的
#解决方案是，将所有的虚拟环境目录全都集中起来，
#比如放到 ~/virtualenvs/，并对不同的虚拟环境使用不同的目录来管理。
#virtualenvwrapper 正是这样做的。并且，它还省去了每次
#开启虚拟环境时候的 source 操作，使得虚拟环境更加好用。

#安装
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3
pip install virtualenvwrapper

#环境设定
export WORKON_HOME='~/.virtualenvs'
source /usr/local/bin/virtualenvwrapper.sh

#Create a new virtualenv in the WORKON_HOME directory
mkvirtualenv spider

#List all of the environments
lsvirtualenv

#show the content of the site-packages directory of the currently-active virtualenv.
lssitepackages

#List or change working virtual environments
workon spider

#退出虚拟环境
deactivate

#删除虚拟环境
rmvirtualenv spider

#--------------------------------
#创建新工程
django-admin.py startproject MyBlog

#创建app
python manage.py startapp article

#start web server
manage.py runserver

#同步生成DB 仅在第一次用
python manage.py migrate

#之后编辑model后，都要执行这两个
python manage.py makemigrations
python manage.py migrate

#创建超级用户
python manage.py createsuperuser

#python交互环境变量设置
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MyBlog.settings")
django.setup()

#settings

## database sqlite3 
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'MyBlog.db'),
    }
}

## Static files (CSS, JavaScript, Images)
  STATICFILES = os.path.join(BASE_DIR, 'static')

```

## Setting
- [LANGUAGE_CODE reference](http://www.i18nguy.com/unicode/language-identifiers.html) 
- [TIME_ZONE reference](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)

```
LANGUAGE_CODE = 'ja'
TIME_ZONE = 'Asia/Tokyo'

LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
```

## The view layer

### libs
```
#views lib
from django.shortcuts import render
from django.http import HttpResponse
from django.conf import settings

from django.views.generic import ListView,DetailView
django.views.generic
__all__ = [
    'View', 'TemplateView', 'RedirectView', 'ArchiveIndexView',
    'YearArchiveView', 'MonthArchiveView', 'WeekArchiveView', 'DayArchiveView',
    'TodayArchiveView', 'DateDetailView', 'DetailView', 'FormView',
    'CreateView', 'UpdateView', 'DeleteView', 'ListView', 'GenericViewError',
]

#常用成员变量和方法
-ListView
template_name
context_object_name
get_queryset

--分页
page_type
paginate_by
page_kwarg

-DetailView
template_name
model
pk_url_kwarg
context_object_name
get_object
get_context_data

-FormView
form_class
template_name
form_valid
form_invalid
get_context_data (第一次显示form和form_invalid时调用)


-RedirectView
get


#urls lib
from django.conf.urls import url,include

#forms lib
from django import forms
from django.forms import ModelForm
from django.forms import widgets

--django user
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import AuthenticationForm,UserCreationForm
from django.contrib.auth import login,logout
```

### urls
```
#eg.
url(r'^$', views.IndexView.as_view(), name='index')
url(r'^page/(?P<page>\d+)$', views.IndexView.as_view(), name='index_page'),
url(r'^article/(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/(?P<article_id>\d+).html$',
        views.ArticleDetailView.as_view(),
        name='detail'),
url(r'^category/(?P<category_name>\S+).html$',views.CategoryDetailView.as_view(),name='category_detail'

#regrex
(?P<year>\d+) group匹配

* 匹配前一个字符0次或无限次
+ 匹配前一个字符1次或无限次
? 匹配前一个字符0次或1次
\d 数字[0-9]
\s 空白字符
\S 非空白字符
\w 单词字符[A-Za-z0-9_]

```
### paginator
```
url(r'^page/(?P<page>\d+)$', views.IndexView.as_view(), name='index_page'),
context = {
                'paginator': paginator,
                'page_obj': page,
                'is_paginated': is_paginated,
                'object_list': queryset
}
```

### tags
```

#tag
from django import template
from django.template.defaultfilters import stringfilter
from django.conf import settings

register = template.Library()

@register.simple_tag
@register.inclusion_tag('blog/tags/breadcrumb.html')

@register.filter(is_safe=True)
@stringfilter

#将函数处理的结果赋值给一个变量
@register.assignment_tag

```

## The model layer
```
#lib
from django.db import models
from django.core.urlresolvers import reverse

#auth
AUTH_USER_MODEL='auth.User'

```


## The template layer

### 配置
```
#TEMPLATES
TEMPLATES 'DIRS': [os.path.join(BASE_DIR, 'templates')]
```

### 代码实例
```
#ModelForm实现例子
class CommentForm(ModelForm):
    url = forms.URLField(label='网址',required=False)
    email = forms.EmailField(label='电子邮箱', required=False)
    name = forms.CharField(label='姓名')
    parent_comment_id = forms.IntegerField(widget=forms.HiddenInput, required= False)


    class Meta:
        model = Comment
        fields = ['body']class CommentForm(ModelForm):
    url = forms.URLField(label='网址',required=False)
    email = forms.EmailField(label='电子邮箱', required=False)
    name = forms.CharField(label='姓名')
    parent_comment_id = forms.IntegerField(widget=forms.HiddenInput, required= False)


    class Meta:
        model = Comment
        fields = ['body']
        
#AuthenticationForm,UserCreationForm实现例子
class LoginForm(AuthenticationForm):
    def __init__(self,*args,**kwargs):
        super(LoginForm,self).__init__(*args,**kwargs)
        self.fields['username'].widget = widgets.TextInput(attrs={'placeholder':'username','class':'form-control'})
        self.fields['password'].widget = widgets.PasswordInput(attrs={'placeholder':'password','class':'form-control'})


class RegisterForm(UserCreationForm):
    def __init__(self,*args,**kwargs):
        super(RegisterForm,self).__init__(*args,**kwargs)

        self.fields['username'].widget = widgets.TextInput(attrs={'placeholder':'username','class':'form-control'})
        self.fields['email'].widget = widgets.EmailInput(attrs={'placeholder':'email','class':'form-control'})
        self.fields['password1'].widget = widgets.PasswordInput(attrs={'placeholder':'password','class':'form-control'})
        self.fields['password2'].widget = widgets.PasswordInput(attrs={'placeholder':'repeat password','class':'form-control'})

    class Meta:
        model = get_user_model()
        fields = ('username','email')
```

### formset
```
from django import forms
class ArticleForm(forms.Form): 
    title = forms.CharField()
    pub_date = forms.DateField()
    
from django.forms import formset_factory
ArticleFormSet = formset_factory(ArticleForm,extra=2)
formset = ArticleFormSet()
for form in formset:
    print(form.as_table())

# 表单内的errors,规则验证
formset.errors
#调单外的逻辑验证
formset.non_form_errors
```

### forms知识点
```
ManyToManyField Django 创建一个中间表来表示ManyToManyField关系。默认情况下，中间表的名称由两个关系表名结合而成。

new_blog=form.save(commit=False) 
new_blog.author=current_user 

##保存时，有两种方式
1.先通过new_blog.save() 保存blog数据，再通过form.save_m2m() manytomany关系到中间表
new_blog.save() 
form.save_m2m() 
2.此方法保存blog数据和保存manytomany关系到中间表
form.save()
```

## The admin layer
```
from django.contrib import admin
admin.site.register(Article)
```

## django部署
- [使用PythonAnyWhere和GitHub免费部署Django网站](https://segmentfault.com/a/1190000009240824)
- [如何在阿里云上部署 Django 应用程序](https://www.alibabacloud.com/zh/getting-started/projects/how-to-deploy-django-application-on-alibaba-cloud)

## ERRORS 
```
{'fraction_non_alphanumeric': 0.14443931702814952, 'fraction_numerical': 0.005933153141274968, 'mean_word_length': 4.9913112164296995, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 6, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '649780', 'n_tokens_mistral': 5797, 'n_tokens_neox': 5821, 'n_words': 945}