Django开发笔记二

时间:2023-03-08 17:46:51

Django开发笔记一

Django开发笔记二

Django开发笔记三

Django开发笔记四

Django开发笔记五

Django开发笔记六

1、xadmin添加主题、修改标题页脚和收起左侧菜单

# *************后台***********************
# 主题
class BaseSetting(object):
enable_themes = True
use_bootswatch = True # 修改标题页脚和收起左侧菜单
class GlobalSetting(object):
site_title = "xx管理系统"
site_footer = "xxxx"
menu_style = "accordion" xadmin.site.register(views.BaseAdminView, BaseSetting)
xadmin.site.register(views.CommAdminView, GlobalSetting)

主题如果未加载(只有默认的和Bootstrap2)参考:https://my.oschina.net/u/2396236/blog/1083251

2、xadmin左侧菜单app文字修改

apps.py:

class UsersConfig(AppConfig):
name = 'users'
verbose_name = u"用户"

__init__.py:

default_app_config = "users.apps.UsersConfig"

3、静态页面跳转:

settings.py:

STATIC_URL = '/static/'

STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)

urls.py:

from django.views.generic import TemplateView

urlpatterns = [
url(r'^admin/', xadmin.site.urls),
url(r'^$', TemplateView.as_view(template_name="test/index.html"), name="index"),
url(r'^login$', TemplateView.as_view(template_name="test/login.html"), name="login"), ]

4、用户登录:

修改urls.py:

from users.views import login
url(r'^login/$', login, name="login"),

user app下views.py:

from django.shortcuts import render
from django.contrib.auth import login as dj_login, authenticate # Create your views here. def login(request):
if request.method == "POST":
user_name = request.POST.get("username", "")
pass_word = request.POST.get("password", "")
user = authenticate(username=user_name, password=pass_word) if user is not None:
dj_login(request, user)
return render(request, "test/index.html", {})
else:
return render(request, "test/login.html", {"msg":"username or password is wrong"}) elif request.method == "GET":
return render(request, "test/login.html", {})

注意和系统函数重名时可以用别名区分,例如:as dj_login

5、添加邮箱认证登录:

settings.py:

AUTHENTICATION_BACKENDS = ('users.views.CustomBackend',)

user app下views.py

# coding=utf-8
from django.shortcuts import render
from django.contrib.auth import login as dj_login, authenticate
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from users.models import UserProfile # Create your views here. # 添加邮箱认证
class CustomBackend(ModelBackend):
def authenticate(self, username=None, password=None, **kwargs):
try:
user = UserProfile.objects.get(Q(username=username) | Q(email=username))
if user.check_password(password):
return user
except Exception as e:
return None

6、在首页区别登录的用户和未登录的用户:

                    {% if request.user.is_authenticated %}
        登录的页面
{% else %}
        未登录的页面
{% endif %}