Django setting配置

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'


STATICFILES_DIRS=((os.path.join(BASE_DIR, 'static')),)
html中
{% load static %}
<link href="/static/bootstrap/css/bootstrap.min.css" rel="stylesheet" >
<link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">


redirect('/home/')    # 重定向

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01',
]

AUTH_USER_MODEL='app01.UserFile'//引用原始的數據表

判斷是否登陸
request.user.is_authenticated
登陸的用戶名
request.user.userprofile.name  命名所有小寫


副本編輯器
ckeditor.com

xadmin
django1.9
adminx.py
class EmailVerifyRecordAdmin(object):
list_display = ['code','email','send_type','send_time']
search_fields = ['code','email','send_type']
list_filter = ['code','email','send_type','send_time']
class BannerAdmin(object):
list_display = ['title', 'image', 'url', 'index','add_time']
search_fields = ['title', 'image', 'url', 'index',]
list_filter = ['title', 'image', 'url', 'index','add_time']


xadmin.site.register(EmailVerifyRecord,EmailVerifyRecordAdmin)
xadmin.site.register(Banner,BannerAdmin)
from  xadmin import  views

樣式:
from  xadmin import  views

# 注意httplib2高版本0.10.3
class BaseSetting(object):
enable_themes = True
use_bootswatch = True
xadmin.site.register(views.BaseAdminView,BaseSetting)
修改全局變量
class GlobalSetting(object):
site_title = "後臺管理系統"
site_footer='本身的'
  menu_style='accordion'
xadmin.site.register(views.CommAdminView,GlobalSetting)

去掉項目英文標題
在apps中設置
class UsersConfig(AppConfig):
name = 'users'
verbose_name = '用戶'
在__init__中設置
default_app_config = 'users.apps.UsersConfig'

在設置跳轉頁面
from django.views.generic import TemplateView
urlpatterns = [
url(r'^xadmin/', xadmin.site.urls),
url(r'^$', TemplateView.as_view(template_name='xx.html'),name='xxx'),
]


redirect('/home/')    # 重定向  打開新頁面

render(request,'login.html',{'msg':msg})#頁面渲染


用戶登陸 方法1
在settingz中
AUTHENTICATION_BACKENDS =('users.viwws.CustomBackend',)


views中
# -*- coding: utf-8 -*-
from django.shortcuts import render

from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.backends import ModelBackend
from .models import UserFile
from django.db.models import Q
# Create your views here.
class CustomBackend(ModelBackend):#自定義郵箱驗證
def authenticate(self, username=None, password=None, **kwargs):
try:
user = UserFile.objects.get(Q(username=username)|Q(email=username))
if user.check_password(password):
return user
except Exception as e:
return None

def jj(request):
if request.method=='POST':
user_name = request.POST.get('username','')
pass_word = request.POST.get('password','')
user = authenticate(user_name=user_name,pass_word=pass_word)#到數據庫中驗證用戶名和密碼
if user is not None:#驗證成功
login(request,user)#登陸
return render(request, '')
else:
return render(request, 'index.html', {})


elif request.method=='GET':
return render(request,'',{})

用戶登陸 方法2:重寫驗證方式CustomBackend
在settingz中
AUTHENTICATION_BACKENDS =('users.viwws.CustomBackend',)

在urls中
from users.views import LoginView
url(r'^xadmin/',LoginView.as_view()),

views中
# -*- coding: utf-8 -*-
from django.shortcuts import render

from django.contrib.auth import authenticate,login
from django.contrib.auth.backends import ModelBackend
from .models import UserFile
from django.db.models import Q
# Create your views here.
class CustomBackend(ModelBackend):#自定義郵箱驗證
def authenticate(self, username=None, password=None, **kwargs):
try:
user = UserFile.objects.get(Q(username=username)|Q(email=username))
if user.check_password(password):
return user
except Exception as e:
return None
from django.views.generic.base import View

class LoginView(View):
def get(self,request):
return render(request, '', {})
def post(self,request):
user_name = request.POST.get('username', '')
pass_word = request.POST.get('password', '')
user = authenticate(user_name=user_name, pass_word=pass_word) # 到數據庫中驗證用戶名和密碼
if user is not None: # 驗證成功
login(request, user) # 登陸
return render(request, '')
else:
return render(request, 'index.html', {})

FORM表單驗證:
from django import forms

class LoginForm(forms.Form):
username = forms.CharField(required=True)
password = forms.CharField(required=True)

from django.views.generic.base import View

class LoginView(View):
def get(self,request):
return render(request, '', {})
def post(self,request):
login_form = LoginForm(request)
if login_form.is_valid():
user_name = request.POST.get('username', '')
pass_word = request.POST.get('password', '')
user = authenticate(user_name=user_name, pass_word=pass_word) # 到數據庫中驗證用戶名和密碼
if user is not None: # 驗證成功
login(request, user) # 登陸
return render(request, '')
else:
return render(request, 'index.html', {'msg': 'error'})

else:
return render(request, 'index.html', {'login_form':login_form})
退出:
from django.contrib.auth import  authenticate,login,logout
logout(request)


靜態文件的引用:
<!DOCTYPE html>
<html lang="en">
{% load staticfiles %}
<head>
<link rel="stylesheet" type="text/css" href="{% static 'css/reset.css' %}">
<meta charset="UTF-8">

<title>Title</title>
</head>
<body>

</body>
</html>


圖片驗證碼框架
django-simple-captcha 0.4.6
註冊時候密碼明文轉換爲密文保存到數據庫中
from django.contrib.auth.hashers import make_password
make_password(password)

發送郵件驗證激活 is_active = True激活狀態 False未激活狀態
在setting.py
EMAIL_HOST='smtp.sina.com'
EMAIL_PORT=25
EMAIL_HOST_USER=''
EMAIL_HOST_PASSWORD=''
EMAIL_USE_TLS=False
EMAIL_FROM=EMAIL_HOST_USER
views中
# 郵箱隨機碼
def generate_str(randomlength=8):
str = ''
chars = 'AaBbCcDdEeFf0123456789'
length = len(chars)-1
for i in range(randomlength):
str +=chars[randomlength.randint(0,length)]
return str


from users.models import EmailVerifyRecord #郵箱類
from django.core.mail import send_mail#郵箱發送
from hh.settings import EMAIL_FROM
def send_register_email(email,type=0):
email_record = EmailVerifyRecord()
code_str=generate_str(16)
email_record.code = code_str
email_record.email = email
email_record.send_type = 0
email_record.save()
email_title = ''
email_body = ''
if type==0:
email_title = '註冊激活鏈接'
email_body = '請點擊下面的鏈接激活你的賬號:http;//127.0.0.1:8000/active/{0}.'.format(code_str)
send_status = send_mail(email_title,email_body,EMAIL_FROM,[email])#email發送者郵箱
if send_status:
pass


圖片保存路徑配置
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.jion(BASE_DIR,'media')

分頁
django-pure-pagination開發庫


自定義分頁插件

#!/usr/bin/env python
#-*- coding:utf-8 -*-
from django.utils.safestring import mark_safejavascript

class Pager(object):
def __init__(self,current_page):
self.current_page = int(current_page)
#把方法僞形成屬性(1)
@property
def start(self):
return (self.current_page-1)*10
@property
def end(self):
return self.current_page*10css

def page_str(self,all_item,base_url):
all_page, div = divmod(all_item, 10)html

if div > 0:
all_page += 1前端

pager_list = []java

if all_page <= 11:
start = 1
end = all_page
else:
if self.current_page <= 6:
start = 1
end = 11 + 1
else:
start = self.current_page - 5
end = self.current_page + 6
if self.current_page + 6 > all_page:
start = all_page - 10
end = all_page + 1python

#把頁面動態起來傳入起始和結束
for i in range(start, end):數據庫

#判斷是否爲當前頁
if i == self.current_page:
temp = '<a style="color:red;font-size:26px;padding: 5px" href="%s?page=%d">%d</a>' % (base_url,i,i)
else:
temp = '<a style="padding: 5px" href="%s?page=%d">%d</a>' % (base_url,i,i)django

# 把標籤拼接而後返回給前端
pager_list.append(temp)bootstrap

#上一頁
if self.current_page > 1:
pre_page = '<a href="%s?page=%d">上一頁</a>' % (base_url, self.current_page - 1)
else:
# javascript:void(0) 什麼都不幹
pre_page = '<a href="javascript:void(0);">上一頁</a>'
#下一頁
if self.current_page >= all_page:
next_page = '<a href="javascript:void(0);">下一頁</a>'
else:
next_page = '<a href="%s?page=%d">下一頁</a>' % (base_url, self.current_page + 1)session

pager_list.insert(0, pre_page)
pager_list.append(next_page)

return mark_safe("".join(pager_list))

相關文章
相關標籤/搜索