大多数情况下,我将平面页面用于一个站点(来自站点框架)。如何为所有创建的平面页面标记现有站点默认值?每次为创建的每个页面选择相同的站点都是浪费时间。有没有办法在模型或保存方法中覆盖它?
4 回答
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
这是我的代码,它有效:
class CustomFlatPage(FlatPage):
def save(self):
super(CustomFlatPage, self).save()
self.sites = [Site.objects.get(pk=1)]
super(CustomFlatPage, self).save()
这是解决原始问题的完整工作代码(为所有创建的平面标记现有站点默认值):
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。前一个是用一个 INSERT 和一个 UPDATE 或两个 UPDATE 击中数据库。
- 通过 using
proxy = True
不需要运行syncbdCustomFlatPage
来为模型创建额外的表。
我采取了不同的方法,猴子修补 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()
这是在 Django 1.4 和 python 2.7.3 下,但也应该适用于旧版本。
哦,请注意,如果您真的想要一个空站点关联,您可以有意取消选择它,因为这只是小部件初始化。随后的编辑将传递一个空列表以呈现为值,这不是无。
比尔,KE1G