• 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_safe

    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*10

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

    if div > 0:
    all_page += 1

    pager_list = []

    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 + 1

    #把页面动态起来传入起始和结束
    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)

    # 把标签拼接然后返回给前端
    pager_list.append(temp)

    #上一页
    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)

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

    return mark_safe("".join(pager_list))

















  • 相关阅读:
    Seasar2:SAStruts:View(JSP)
    Seaser2:SAStruts:エラーメッセージの設定
    Seaser2:SAStruts:アクションとアクションフォーム(Struts)
    SAStruts アクションにJSONを返すメソッドを作成してみる
    S2JDBC テーブルを利用した独自仕様のid採番メソッド
    【C++ 异常】error: jump to case label [fpermissive]
    MusicXML 3.0 (15) 倚音
    MusicXML 3.0 (9) 小节线、反复线、终止线
    MusicXML 3.0 (13) 歌词
    MusicXML 3.0 (10) 换行、换页
  • 原文地址:https://www.cnblogs.com/zhang997050423/p/7079773.html
Copyright © 2020-2023  润新知