Django 平面页面默认站点

发布于 2024-10-14 15:41:18 字数 99 浏览 2 评论 0原文

我主要在一个网站上使用平面页面(来自网站框架)。如何为所有创建的平面页面标记现有站点默认值? 每次为创建的每个页面选择相同的站点都是浪费时间。有什么方法可以在模型或保存方法中覆盖它吗?

mostly I use flatpages for one site (from sites framework). How can I mark existing site default for all created flatpages?
It is waste of time every time to choose same site for every page created. Is there any way to override this in models or save method?

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

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

发布评论

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

评论(4

记忆里有你的影子 2024-10-21 15:41:18

允许站点字段(models.py -> FlatPage.sites)中为空白并将其放入模型表单(admin.py -> FlatPageForm)中

def clean_sites(self):
    sites = self.cleaned_data.get('sites')
    print sites
    return [Site.objects.get(id=settings.SITE_ID)]

编辑:
我想出了一个更好的解决方案。
这使得当前站点已经专注于ManyToMany站点领域。编辑 flatpages/admin.py。在文件开头添加:from django.contrib.sites.models import Site并将以下代码放入class FlatPageAdmin中:

    def formfield_for_manytomany(self, db_field, request=None, **kwargs):
    if db_field.name == "sites":
        kwargs["initial"] = [Site.objects.get_current()]
    return super(FlatPageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

sites字段中不需要留空在 FlatPage 模型中

allow for blank in sites field (models.py -> FlatPage.sites) and put this in your model Form (admin.py -> FlatPageForm)

def clean_sites(self):
    sites = self.cleaned_data.get('sites')
    print sites
    return [Site.objects.get(id=settings.SITE_ID)]

edit:
I've come up with a better solution.
This makes current site already focused in ManyToMany sites field. Edit flatpages/admin.py. Add :from django.contrib.sites.models import Site in the beggining of file and put following code into class FlatPageAdmin:

    def formfield_for_manytomany(self, db_field, request=None, **kwargs):
    if db_field.name == "sites":
        kwargs["initial"] = [Site.objects.get_current()]
    return super(FlatPageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

There is no need to allow for blank in sites field in FlatPage model

栩栩如生 2024-10-21 15:41:18

这是我的代码,它有效:

class CustomFlatPage(FlatPage):
    def save(self):
        super(CustomFlatPage, self).save()
        self.sites = [Site.objects.get(pk=1)]
        super(CustomFlatPage, self).save()

Here is my code, it works:

class CustomFlatPage(FlatPage):
    def save(self):
        super(CustomFlatPage, self).save()
        self.sites = [Site.objects.get(pk=1)]
        super(CustomFlatPage, self).save()
阪姬 2024-10-21 15:41:18

这是解决原始问题的一段完全有效的代码(标记所有创建的平面页面的现有站点默认值):

from django.conf import settings
from django.contrib.flatpages.models import FlatPage
from django.contrib.sites.models import Site

class CustomFlatPage(FlatPage):
    class Meta:
        proxy = True

    def save(self):
        self.sites = [Site.objects.get(pk=settings.SITE_ID)]
        super(CustomFlatPage, self).save()

此外,此解决方案:

  • 仅在数据库中运行一个 INSERT 或一个 UPDATE。前一种方法是通过一次插入和一次更新或两次更新来访问数据库。
  • 通过使用 proxy = True 无需运行 syncbd 即可为 CustomFlatPage 模型创建额外的表。

Here is a completely working piece of code solving the original problem (to mark existing site default for all created flatpages):

from django.conf import settings
from django.contrib.flatpages.models import FlatPage
from django.contrib.sites.models import Site

class CustomFlatPage(FlatPage):
    class Meta:
        proxy = True

    def save(self):
        self.sites = [Site.objects.get(pk=settings.SITE_ID)]
        super(CustomFlatPage, self).save()

Also this solution:

  • Only runs one INSERT or one UPDATE in the DB. The previous one was hitting the DB with one INSERT and one UPDATE, or two UPDATES.
  • By using proxy = True is not necessary to run syncbd in order to create an extra table for CustomFlatPage model.
娇俏 2024-10-21 15:41:18

我采取了不同的方法,猴子修补 FlatpageForm Meta 以使用网站的自定义小部件。

from django.forms import SelectMultiple
from django.conf import settings
from django.contrib.flatpages.forms import FlatpageForm

class PreSelectDefaultSiteOnCreateSelectMultiple(SelectMultiple):
    def render(self, name, value, attrs=None, choices=()):
        if value is None:
            # None in the add form, a list, possibly empty, in
            # the edit form.  So we're adding a new instance here.
            value = [settings.SITE_ID]
        return super(PreSelectDefaultSiteOnCreateSelectMultiple, self
                     ).render(name, value, attrs, choices)

def flatpages():
    """Hack the sites field widget.
    """
    fpafm = FlatpageForm.Meta
    if getattr(fpafm, 'widgets', None) is None:
        fpafm.widgets = {}
    fpafm.widgets['sites'] = PreSelectDefaultSiteOnCreateSelectMultiple

在使用管理之前,您必须从某个地方调用 flatpages() 。我将上面的代码放在包 Monkey_patches 的 admin.py 模块中,然后在我的根 urls.py 中(第一次请求传入时导入),我放入:

from monkey_patches.admin import flatpages
flatpages()

This is under Django 1.4 with python 2.7.3, but也应该适用于旧版本。

哦,请注意,如果您确实想要一个空的站点关联,您可以有意取消选择它,因为这只是小部件初始化。后续编辑将传递一个空列表以呈现为值,该值不是 None。

比尔,KE1G

I took a different approach, monkey patching the FlatpageForm Meta to use a custom widget for sites.

from django.forms import SelectMultiple
from django.conf import settings
from django.contrib.flatpages.forms import FlatpageForm

class PreSelectDefaultSiteOnCreateSelectMultiple(SelectMultiple):
    def render(self, name, value, attrs=None, choices=()):
        if value is None:
            # None in the add form, a list, possibly empty, in
            # the edit form.  So we're adding a new instance here.
            value = [settings.SITE_ID]
        return super(PreSelectDefaultSiteOnCreateSelectMultiple, self
                     ).render(name, value, attrs, choices)

def flatpages():
    """Hack the sites field widget.
    """
    fpafm = FlatpageForm.Meta
    if getattr(fpafm, 'widgets', None) is None:
        fpafm.widgets = {}
    fpafm.widgets['sites'] = PreSelectDefaultSiteOnCreateSelectMultiple

You must call flatpages() from somewhere before the admin might be used. I put the code above in a module admin.py in a package monkey_patches, then in my root urls.py, which gets imported the first time a request comes in, I put:

from monkey_patches.admin import flatpages
flatpages()

This is under Django 1.4 with python 2.7.3, but should work for older versions too.

Oh, and note that if you really want an empty sites association, you can deselect it intentionally, since this is just widget initialization. Subsequent edits will pass an empty list to render as value, which isn't None.

Bill, KE1G

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