Django:如何使用自定义模板标签动态获取字段值?

发布于 2024-09-30 09:19:06 字数 2347 浏览 3 评论 0原文

我正在编写一个通用模板标签,它可以根据模板文件中的用户输入动态返回模型的字段值。这个想法遵循《实用Django项目第二版》一书中提到的,但是书本版本是获取一个对象列表,我只想获取一个对象的值。我想获取网站设置(标题、标语等)并动态传入模板,这样我就不必再次编写代码来获取每个字段的值。

这是我到目前为止所做的。

为模型定义一个 admin.py(这里不包括,因为它不重要)

定义了一个模型:

from django.db import models
from django.contrib.sites.models import Site

class Naming(models.Model):
    title = models.CharField(max_length=250)
    site_id = models.ForeignKey(Site)
    tagline = models.CharField(max_length=250)
    description = models.TextField(blank=True)

    def __unicode__(self):
        return self.title

定义了一个模板标记文件,注释行这是我陷入困境的地方

from django.db.models import get_model
from django.contrib.sites.models import Site
from django import template

def do_site_att(parser, token):
    bits = token.split_contents()
    if len(bits) != 5:
        raise template.TemplateSyntaxError("'get_site_att' tag takes exactly four arguments")
    model_args = bits[1].split('.')
    if len(model_args) != 2:
        raise template.TemplateSyntaxError("First argument to 'get_site_att' must be an 'application name'.'model name' string.")
    model = get_model(*model_args)
    if model is None:
        raise template.TemplateSyntaxError("'get_site_att' tag got an invalid model: %s." % bits[1])
    return ContentNode(model, bits[2], bits[4])

class ContentNode(template.Node):
    def __init__(self, model, field, varname):
        self.model = model
        self.field = field
        self.varname = varname

    def render(self, context):
        current_site = Site.objects.get_current()
        try:
            var = self.model.objects.get(site_id=current_site.id)
            context[self.varname] = var.title #I get stuck here because it not accepts input like var.field (I have extract the field value above)
        except:
            context[self.varname] = "Value not found"
        return ''


register = template.Library()
register.tag('get_site_att', do_site_att)

base.html 中的模板查询:

{% load general_tags %}
{% get_site_att general.Naming title as title %}
<h1 id="branding">{{title}}</h1>
{% get_site_att general.Naming tagline as tagline %}
<h2 id="tagline">{{tagline}}</h2>

我已经尝试了我能想到的所有可能的方法,但就是无法让它工作。非常感谢任何帮助。谢谢。

I'm writing a generic template tag that could return a model's field value dynamically based on user inputs in template files. The idea follows which mentioned in the book "Practical Django Project 2nd Edition", but the book version is getting a list of objects where I want to get only a object's value. I want to get the site settings (Title, Tagline etc.) and pass in the template dynamically so that I don't have to write the code again to get each field's value.

Here is what I have done so far.

Define an admin.py for the model (not included here because it's not important)

Defined a model:

from django.db import models
from django.contrib.sites.models import Site

class Naming(models.Model):
    title = models.CharField(max_length=250)
    site_id = models.ForeignKey(Site)
    tagline = models.CharField(max_length=250)
    description = models.TextField(blank=True)

    def __unicode__(self):
        return self.title

Defined a template tag file, the commented line is where I get stuck

from django.db.models import get_model
from django.contrib.sites.models import Site
from django import template

def do_site_att(parser, token):
    bits = token.split_contents()
    if len(bits) != 5:
        raise template.TemplateSyntaxError("'get_site_att' tag takes exactly four arguments")
    model_args = bits[1].split('.')
    if len(model_args) != 2:
        raise template.TemplateSyntaxError("First argument to 'get_site_att' must be an 'application name'.'model name' string.")
    model = get_model(*model_args)
    if model is None:
        raise template.TemplateSyntaxError("'get_site_att' tag got an invalid model: %s." % bits[1])
    return ContentNode(model, bits[2], bits[4])

class ContentNode(template.Node):
    def __init__(self, model, field, varname):
        self.model = model
        self.field = field
        self.varname = varname

    def render(self, context):
        current_site = Site.objects.get_current()
        try:
            var = self.model.objects.get(site_id=current_site.id)
            context[self.varname] = var.title #I get stuck here because it not accepts input like var.field (I have extract the field value above)
        except:
            context[self.varname] = "Value not found"
        return ''


register = template.Library()
register.tag('get_site_att', do_site_att)

The template query in base.html:

{% load general_tags %}
{% get_site_att general.Naming title as title %}
<h1 id="branding">{{title}}</h1>
{% get_site_att general.Naming tagline as tagline %}
<h2 id="tagline">{{tagline}}</h2>

I have tried all the possible ways I can think of, but just can't get it works. Any help is really appreciated. Thanks.

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

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

发布评论

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

评论(2

谁的年少不轻狂 2024-10-07 09:19:06

我找到了解决方案:

在注释行上,使用以下代码:

var = self.model.objects.get(site_id__exact=current_site.id)
context[self.varname] = var.__dict__[self.field]#this will get the field's value dynamically, which is what I was looking for

I found the solution for this:

on the commented lines, use this code:

var = self.model.objects.get(site_id__exact=current_site.id)
context[self.varname] = var.__dict__[self.field]#this will get the field's value dynamically, which is what I was looking for
南巷近海 2024-10-07 09:19:06

Python 中获取其名称在另一个变量中具有名称的属性的常规方法是使用 getattr。

context[self.varname] = getattr(var, self.field)

The normal way in Python to get an attribute whose name you have in another variable is to use getattr.

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