Django:允许管理员用户编辑站点范围的设置吗?

发布于 2024-10-15 05:41:26 字数 450 浏览 3 评论 0原文

我有一个 Django 站点,我想允许一些站点范围的设置:

ADMIN_EMAIL - email address for an administrative user
REMINDER_TEXT - email text for an email that the site will generate once a week

在管理界面中进行编辑。

做到这一点最明智的方法是什么?我应该将这些值存储在 settings.py 中,还是数据库中的某个位置?

这个上一个问题似乎相关,但我不知道我认为这个问题已经得到了充分的回答。

谢谢!

I have a Django site, and I'd like to allow a couple of site-wide settings:

ADMIN_EMAIL - email address for an administrative user
REMINDER_TEXT - email text for an email that the site will generate once a week

to be edited in the admin interface.

What is the most sensible way to do this? Should I store these values in settings.py, or somewhere in the database?

This previous SO question seems to be related, but I don't think it's ever been fully answered.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

泛泛之交 2024-10-22 05:41:26

我尝试过 dbsettings(以及它在 github 上的较新分支),它们很有用 - 但对于我的需求来说有点太重了。相反,我实现了一种更简单的方法。我使用 JSONField (来自 Postgres 9.3)来完成它 - 但您可能更喜欢使用 TextField (使用 max_length=1000 或类似的),因为向人们解释如何输入字符串而不是 JSON 更简单:

1)首先,构建您的自己的设置模型(可能在 core/models.py 中):

class Setting(models.Model):
    """
    Model for site-wide settings.
    """
    name = models.CharField(max_length=200, help_text="Name of site-wide variable")
    value = JSONField(null=True, blank=True, help_text="Value of site-wide variable that scripts can reference - must be valid JSON")

    def __unicode__(self):
        return self.name

2)然后,添加管理界面(在 core/admin.py 中):

class SettingAdmin(admin.ModelAdmin):
    list_display = ['name', 'value']

admin.site.register(Setting, SettingAdmin)

3)构建并运行迁移:

python manage.py schemamigration core --auto
python manage.py migrate core

4)添加到 base.html 的顶部:

<script type="text/javascript">
    //Auto-exported site-wide settings
    {% autoescape off %}var site_settings = {{ settings|safe|default:"{}" }};{% endautoescape %}
</script>

5 )构建一个“注入器”,将代码添加到每个请求(可能在 core/contextprocessors.py 中)

from models import Setting
import json

def app_settings(request):
    """Global values to pass to templates"""
    settings_dict = dict()
    settings = dict()
    for obj in Setting.objects.all():
        settings[obj.name] = obj.value
    settings_dict['settings'] = json.dumps(settings)
    return settings_dict

5) 然后,将上下文处理器添加到您的站点 settings.py:

TEMPLATE_CONTEXT_PROCESSORS = (
    ...,
    '<yourapp>.core.contextprocessors.app_settings',
)

6) 通过浏览器登录到您的管理页面并创建一个设置:

http://yoursite/admin/core/setting/
Add a new setting, something like:
    cell_status_colors
with a value of: 
    ["green","red"] (note this has to be valid JSON, so use quotes around strings)

or:
    daily_header
with a value of:
    {"text":"Tomorrow only, free shipping!"}

7) 最后,每个 javascript 文件都应该能够通过标准 JS 调用它们:

var colors = site_settings.cell_status_colors || ["green","red"];
var msg_text = site_settings.daily_header || {"text":""};

I've tried dbsettings (as well as the newer fork of it on github), and they are useful - but a bit too heavy-weight for my needs. Instead, I implemented a simpler method. I did it using a JSONField (from Postgres 9.3) - but you might prefer to use a TextField (use max_length=1000 or somesuch) as it's simpler to explain to people how to enter a string instead of JSON:

1) First, build your own Settings Model (maybe in core/models.py):

class Setting(models.Model):
    """
    Model for site-wide settings.
    """
    name = models.CharField(max_length=200, help_text="Name of site-wide variable")
    value = JSONField(null=True, blank=True, help_text="Value of site-wide variable that scripts can reference - must be valid JSON")

    def __unicode__(self):
        return self.name

2) Then, add an admin interface (in core/admin.py):

class SettingAdmin(admin.ModelAdmin):
    list_display = ['name', 'value']

admin.site.register(Setting, SettingAdmin)

3) Build and run your migrations:

python manage.py schemamigration core --auto
python manage.py migrate core

4) Add to the top of base.html:

<script type="text/javascript">
    //Auto-exported site-wide settings
    {% autoescape off %}var site_settings = {{ settings|safe|default:"{}" }};{% endautoescape %}
</script>

5) Build an 'injector' that adds code to every request (likely in core/contextprocessors.py)

from models import Setting
import json

def app_settings(request):
    """Global values to pass to templates"""
    settings_dict = dict()
    settings = dict()
    for obj in Setting.objects.all():
        settings[obj.name] = obj.value
    settings_dict['settings'] = json.dumps(settings)
    return settings_dict

5) Then, add the context processors to your site settings.py:

TEMPLATE_CONTEXT_PROCESSORS = (
    ...,
    '<yourapp>.core.contextprocessors.app_settings',
)

6) Log into your admin page via browser and create a setting:

http://yoursite/admin/core/setting/
Add a new setting, something like:
    cell_status_colors
with a value of: 
    ["green","red"] (note this has to be valid JSON, so use quotes around strings)

or:
    daily_header
with a value of:
    {"text":"Tomorrow only, free shipping!"}

7) And finally, each of your javascript files should be able to call these via standard JS:

var colors = site_settings.cell_status_colors || ["green","red"];
var msg_text = site_settings.daily_header || {"text":""};
最丧也最甜 2024-10-22 05:41:26

理想情况下,settings.py 必须很少被访问,因为每次访问都会暴露重要数据(例如数据库密码)。因此,存储额外设置的最佳位置绝对是数据库表 - 一个两列表,带有设置键和实际设置数据就足够了。

Ideally, settings.py has to be accessed very rarely, because each access consists in exposing important data (db password for instance). So the best place to store extra settings is definitely a database table - a two column table, with the settings key and the actual settings data will suffice.

醉态萌生 2024-10-22 05:41:26

有一些应用程序允许 django 管理员通过站点范围定义和使用某些设置...其中一个这样的应用程序(我使用的)是 dbsettings...

数据库设置应用程序...

There are some applications, that allows django admins to define and use some settings through site-wide... One of those such applications(which i used) is dbsettings...

dbsettings applicaton...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文