我有一个Django应用程序,并试图使一些特定的模型信息可更改,而该网站是加载。例如,我希望能够根据我在Django的管理面板上所做的更改来更改页面上的某些图像(横幅等)。此外,我想为我的社交媒体链接创建一个预先填充的迁移列表,可以在django管理页面中进行编辑。我的具体例子是我所有的社交媒体链接。我想把我的社交媒体链接放在一个模型'Facebook Url“= 'www.facebook.com/mypage中。然后我想用点符号{{ project_settings.facebook.url }}把这些链接放在整个页面中。最简单的方法是什么。我不认为我想把上下文放在所有视图中,因为我想让每个页面都有上下文。在我的页脚中,它在每个页面上。背景图像也在几个不同的页面上。
发布于 2018-04-23 10:45:15
我已经完成了您想要做的事情,创建了CustomText和CustomImage模型,如下所示:
class CustomText(models.Model):
name = models.SlugField()
plain_text = models.TextField("Plain/Markdown Text", blank=True)
html_text = models.TextField("HTML Text", blank=True)
auto_render = models.BooleanField("Render to HTML using Markdown (on save)", default=True)
(... implementation of text->html omitted )
class CustomImage(models.Model):
name = models.SlugField()
description = models.TextField("Description", null=True, blank=True)
image = models.ImageField("Custom Image", upload_to="custom_images/", null=True, blank=True)然后我添加了myapp/templatetags/custom_resources.py,这是一对模板标记,用于从这些模型中检索文本或图像:
from django import template
from django.utils.safestring import mark_safe
from myapp.models import CustomImage, CustomText
register = template.Library()
@register.simple_tag
def custom_image(image_name):
cimage = CustomImage.objects.filter(name=image_name).first()
return cimage.image.url if cimage else "custom_image_%s_not_found" % image_name
@register.simple_tag
@mark_safe
def custom_text(text_name):
text = CustomText.objects.filter(name=text_name).first()
return text.html_text if text else "Custom text <%s> not found." % text_name最后,在您的模板中,加载模板标记,然后将模板标记与您想要的资源的适当插件一起使用。
{% load custom_resources %}
...
{% custom_text 'custom_text_slug' %}https://stackoverflow.com/questions/49972502
复制相似问题