django不用在数据库中创建新的user表而使用它的后台管理功能

来源:互联网 发布:python 程序定时执行 编辑:程序博客网 时间:2024/05/29 14:58

在一个项目中经常要对远端的一个数据库中的数据做修改,每次都写sql感觉很麻烦,就想到能不能直接利用django的后台管理功能呢,当然是可以的,但是要登录django的后台使用它的管理功能必须在对应的数据库创建django后台管理需要的user和Log相关的表,而这个又是不可能的,那能不能不创建user表而仅仅是使用它的后台管理功能呢,答案是可以的

django后台登录需要输入用户名、密码,用户登录验证的backend默认是django.contrib.auth.backends,而它采用的是数据库表的验证,为了不创建新表,我们需要修改登录验证的backends,

修改的方法很简单,在setting.py中添加配置

AUTHENTICATION_BACKENDS = ["houtai.extend.auth.backends.SimpleBackend"]#用户验证的Backend

然后要实现SimpleBackend,验证后需要返回一个User对象,所以还需要实现一个SingleUser类

from __future__ import unicode_literalsfrom houtai.extend.auth.user import SingleUserclass SimpleBackend(object):    """    Authenticates against settings.AUTH_USER_MODEL.    """    def authenticate(self, username=None, password=None):        cur_user = SingleUser()        if cur_user.validate(username,password):            return cur_user            def get_user(self, user_id):        return SingleUser()

from houtai.extend.common import Singletonclass SingleUser(Singleton):    username = "admin"    password = "111111"    is_active = 1    is_staff =1    is_superuser =1    pk = '123456'           def validate(self,username,password):        if username and password:            if username == self.username and password == self.password:                return True        return False    def save(self,update_fields=['last_login']):        return    def has_module_perms(self, app_label):        """        Returns True if the user has any permissions in the given app label.        Uses pretty much the same logic as has_perm, above.        """        # Active superusers have all permissions.        if self.is_active and self.is_superuser:            return True        return False    def has_perm(self, perm, obj=None):        return True

有了上面的backends就能够用admin:111111登录到后台,单很快就会出现下面这个错误:

"Table 'test.django_content_type' doesn't exist"
这时候需要做下面三件事才能搞定:

1、修改admin后台首页的模板:

在url.py中添加admin.site.index_template = 'houtai/index.html'

index.html

{% extends "admin/base_site.html" %}{% load i18n admin_static %}{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/dashboard.css" %}" />{% endblock %}{% block coltype %}colMS{% endblock %}{% block bodyclass %}dashboard{% endblock %}{% block breadcrumbs %}{% endblock %}{% block content %}<div id="content-main">{% if app_list %}    {% for app in app_list %}        <div class="app-{{ app.app_label }} module">        <table>        <caption>            <a href="{{ app.app_url }}" class="section" title="{% blocktrans with name=app.name %}Models in the {{ name }} application{% endblocktrans %}">                {% blocktrans with name=app.name %}{{ name }}{% endblocktrans %}            </a>        </caption>        {% for model in app.models %}            <tr class="model-{{ model.object_name|lower }}">            {% if model.admin_url %}                <th scope="row"><a href="{{ model.admin_url }}">{{ model.name }}</a></th>            {% else %}                <th scope="row">{{ model.name }}</th>            {% endif %}            {% if model.add_url %}                <td><a href="{{ model.add_url }}" class="addlink">{% trans 'Add' %}</a></td>            {% else %}                <td> </td>            {% endif %}            {% if model.admin_url %}                <td><a href="{{ model.admin_url }}" class="changelink">{% trans 'Change' %}</a></td>            {% else %}                <td> </td>            {% endif %}            </tr>        {% endfor %}        </table>        </div>    {% endfor %}{% else %}    <p>{% trans "You don't have permission to edit anything." %}</p>{% endif %}</div>{% endblock %}

2、修改django.contrib.admin.options.py

修改:

action_list = LogEntry.objects.filter(                object_id=unquote(object_id),                content_type__id__exact=ContentType.objects.get_for_model(model).id            ).select_related().order_by('action_time')
为:

if settings.LOGGING != None:            action_list = LogEntry.objects.filter(                object_id=unquote(object_id),                content_type__id__exact=ContentType.objects.get_for_model(model).id            ).select_related().order_by('action_time')

修改:

from django.contrib.admin.models import LogEntry, ADDITION            LogEntry.objects.log_action(                user_id=request.user.pk,                content_type_id=ContentType.objects.get_for_model(object).pk,                object_id=object.pk,                object_repr=force_text(object),                action_flag=ADDITION            )

为:

if settings.LOGGING != None:            from django.contrib.admin.models import LogEntry, ADDITION            LogEntry.objects.log_action(                user_id=request.user.pk,                content_type_id=ContentType.objects.get_for_model(object).pk,                object_id=object.pk,                object_repr=force_text(object),                action_flag=ADDITION            )

修改:

from django.contrib.admin.models import LogEntry, CHANGE            LogEntry.objects.log_action(                user_id=request.user.pk,                content_type_id=ContentType.objects.get_for_model(object).pk,                object_id=object.pk,                object_repr=force_text(object),                action_flag=CHANGE,                change_message=message            )

为:

if settings.LOGGING != None:            from django.contrib.admin.models import LogEntry, CHANGE            LogEntry.objects.log_action(                user_id=request.user.pk,                content_type_id=ContentType.objects.get_for_model(object).pk,                object_id=object.pk,                object_repr=force_text(object),                action_flag=CHANGE,                change_message=message            )

修改:

from django.contrib.admin.models import LogEntry, DELETION            LogEntry.objects.log_action(                user_id=request.user.pk,                content_type_id=ContentType.objects.get_for_model(self.model).pk,                object_id=object.pk,                object_repr=object_repr,                action_flag=DELETION            )
为:

if settings.LOGGING != None:            from django.contrib.admin.models import LogEntry, DELETION            LogEntry.objects.log_action(                user_id=request.user.pk,                content_type_id=ContentType.objects.get_for_model(self.model).pk,                object_id=object.pk,                object_repr=object_repr,                action_flag=DELETION            )

3、在setting.py中设置Loging为None

LOGGING  = None#关闭后台日志记录功能

至此就可以用admin:111111登录后台管理远程的数据库了