标签归档:django-templates

创建动态选择字段

问题:创建动态选择字段

我在尝试了解如何在Django中创建动态选择字段时遇到了一些麻烦。我有一个模型设置类似:

class rider(models.Model):
     user = models.ForeignKey(User)
     waypoint = models.ManyToManyField(Waypoint)

class Waypoint(models.Model):
     lat = models.FloatField()
     lng = models.FloatField()

我想做的是创建一个选择字段whos的值是与该骑手相关联的航点(将是登录的人)。

目前,我以如下形式覆盖init:

class waypointForm(forms.Form):
     def __init__(self, *args, **kwargs):
          super(joinTripForm, self).__init__(*args, **kwargs)
          self.fields['waypoints'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in Waypoint.objects.all()])

但是所有要做的就是列出所有路标,它们与任何特定的骑手都没有关联。有任何想法吗?谢谢。

I’m having some trouble trying to understand how to create a dynamic choice field in django. I have a model set up something like:

class rider(models.Model):
     user = models.ForeignKey(User)
     waypoint = models.ManyToManyField(Waypoint)

class Waypoint(models.Model):
     lat = models.FloatField()
     lng = models.FloatField()

What I’m trying to do is create a choice Field whos values are the waypoints associated with that rider (which would be the person logged in).

Currently I’m overriding init in my forms like so:

class waypointForm(forms.Form):
     def __init__(self, *args, **kwargs):
          super(joinTripForm, self).__init__(*args, **kwargs)
          self.fields['waypoints'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in Waypoint.objects.all()])

But all that does is list all the waypoints, they’re not associated with any particular rider. Any ideas? Thanks.


回答 0

您可以通过将用户传递给表单init来过滤航点

class waypointForm(forms.Form):
    def __init__(self, user, *args, **kwargs):
        super(waypointForm, self).__init__(*args, **kwargs)
        self.fields['waypoints'] = forms.ChoiceField(
            choices=[(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
        )

您在启动表单时的视线通过了用户

form = waypointForm(user)

在模型形式的情况下

class waypointForm(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        super(waypointForm, self).__init__(*args, **kwargs)
        self.fields['waypoints'] = forms.ModelChoiceField(
            queryset=Waypoint.objects.filter(user=user)
        )

    class Meta:
        model = Waypoint

you can filter the waypoints by passing the user to the form init

class waypointForm(forms.Form):
    def __init__(self, user, *args, **kwargs):
        super(waypointForm, self).__init__(*args, **kwargs)
        self.fields['waypoints'] = forms.ChoiceField(
            choices=[(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
        )

from your view while initiating the form pass the user

form = waypointForm(user)

in case of model form

class waypointForm(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        super(waypointForm, self).__init__(*args, **kwargs)
        self.fields['waypoints'] = forms.ModelChoiceField(
            queryset=Waypoint.objects.filter(user=user)
        )

    class Meta:
        model = Waypoint

回答 1

有针对您的问题的内置解决方案:ModelChoiceField

通常,ModelForm当您需要创建/更改数据库对象时,总是值得尝试使用。在95%的情况下都有效,并且比创建自己的实现要干净得多。

There’s built-in solution for your problem: ModelChoiceField.

Generally, it’s always worth trying to use ModelForm when you need to create/change database objects. Works in 95% of the cases and it’s much cleaner than creating your own implementation.


回答 2

问题是你什么时候做

def __init__(self, user, *args, **kwargs):
    super(waypointForm, self).__init__(*args, **kwargs)
    self.fields['waypoints'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in Waypoint.objects.filter(user=user)])

在更新请求中,先前的值将丢失!

the problem is when you do

def __init__(self, user, *args, **kwargs):
    super(waypointForm, self).__init__(*args, **kwargs)
    self.fields['waypoints'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in Waypoint.objects.filter(user=user)])

in a update request, the previous value will lost!


回答 3

在初始化骑乘者实例时将其传递给表单怎么样?

class WaypointForm(forms.Form):
    def __init__(self, rider, *args, **kwargs):
      super(joinTripForm, self).__init__(*args, **kwargs)
      qs = rider.Waypoint_set.all()
      self.fields['waypoints'] = forms.ChoiceField(choices=[(o.id, str(o)) for o in qs])

# In view:
rider = request.user
form = WaypointForm(rider) 

How about passing the rider instance to the form while initializing it?

class WaypointForm(forms.Form):
    def __init__(self, rider, *args, **kwargs):
      super(joinTripForm, self).__init__(*args, **kwargs)
      qs = rider.Waypoint_set.all()
      self.fields['waypoints'] = forms.ChoiceField(choices=[(o.id, str(o)) for o in qs])

# In view:
rider = request.user
form = WaypointForm(rider) 

回答 4

在正常选择字段下的工作解决方案下。我的问题是,每个用户都基于很少的条件有自己的CUSTOM选择字段选项。

class SupportForm(BaseForm):

    affiliated = ChoiceField(required=False, label='Fieldname', choices=[], widget=Select(attrs={'onchange': 'sysAdminCheck();'}))

    def __init__(self, *args, **kwargs):

        self.request = kwargs.pop('request', None)
        grid_id = get_user_from_request(self.request)
        for l in get_all_choices().filter(user=user_id):
            admin = 'y' if l in self.core else 'n'
            choice = (('%s_%s' % (l.name, admin)), ('%s' % l.name))
            self.affiliated_choices.append(choice)
        super(SupportForm, self).__init__(*args, **kwargs)
        self.fields['affiliated'].choices = self.affiliated_choice

Underneath working solution with normal choice field. my problem was that each user have their own CUSTOM choicefield options based on few conditions.

class SupportForm(BaseForm):

    affiliated = ChoiceField(required=False, label='Fieldname', choices=[], widget=Select(attrs={'onchange': 'sysAdminCheck();'}))

    def __init__(self, *args, **kwargs):

        self.request = kwargs.pop('request', None)
        grid_id = get_user_from_request(self.request)
        for l in get_all_choices().filter(user=user_id):
            admin = 'y' if l in self.core else 'n'
            choice = (('%s_%s' % (l.name, admin)), ('%s' % l.name))
            self.affiliated_choices.append(choice)
        super(SupportForm, self).__init__(*args, **kwargs)
        self.fields['affiliated'].choices = self.affiliated_choice

回答 5

正如Breedly和Liang指出的那样,Ashok的解决方案将阻止您在发布表单时获取选择值。

一种稍微不同但仍然不完善的解决方法是:

class waypointForm(forms.Form):
    def __init__(self, user, *args, **kwargs):
        self.base_fields['waypoints'].choices = self._do_the_choicy_thing()
        super(waypointForm, self).__init__(*args, **kwargs)

但是,这可能会导致一些并发问题。

As pointed by Breedly and Liang, Ashok’s solution will prevent you from getting the select value when posting the form.

One slightly different, but still imperfect, way to solve that would be:

class waypointForm(forms.Form):
    def __init__(self, user, *args, **kwargs):
        self.base_fields['waypoints'].choices = self._do_the_choicy_thing()
        super(waypointForm, self).__init__(*args, **kwargs)

This could cause some concurrence problems, though.


回答 6

您可以将字段声明为表单的一流属性,并且可以动态设置选项:

class WaypointForm(forms.Form):
    waypoints = forms.ChoiceField(choices=[])

    def __init__(self, user, *args, **kwargs):
        super().__init__(*args, **kwargs)
        waypoint_choices = [(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
        self.fields['waypoints'].choices = waypoint_choices

您也可以使用ModelChoiceField并以类似方式在init上设置queryset。

You can declare the field as a first-class attribute of your form and just set choices dynamically:

class WaypointForm(forms.Form):
    waypoints = forms.ChoiceField(choices=[])

    def __init__(self, user, *args, **kwargs):
        super().__init__(*args, **kwargs)
        waypoint_choices = [(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
        self.fields['waypoints'].choices = waypoint_choices

You can also use a ModelChoiceField and set the queryset on init in a similar manner.


回答 7

如果您需要django admin中的动态选择字段;这适用于Django> = 2.1。

class CarAdminForm(forms.ModelForm):
    class Meta:
        model = Car

    def __init__(self, *args, **kwargs):
        super(CarForm, self).__init__(*args, **kwargs)

        # Now you can make it dynamic.
        choices = (
            ('audi', 'Audi'),
            ('tesla', 'Tesla')
        )

        self.fields.get('car_field').choices = choices

    car_field = forms.ChoiceField(choices=[])

@admin.register(Car)
class CarAdmin(admin.ModelAdmin):
    form = CarAdminForm

希望这可以帮助。

If you need a dynamic choice field in django admin; This works for django >=2.1.

class CarAdminForm(forms.ModelForm):
    class Meta:
        model = Car

    def __init__(self, *args, **kwargs):
        super(CarForm, self).__init__(*args, **kwargs)

        # Now you can make it dynamic.
        choices = (
            ('audi', 'Audi'),
            ('tesla', 'Tesla')
        )

        self.fields.get('car_field').choices = choices

    car_field = forms.ChoiceField(choices=[])

@admin.register(Car)
class CarAdmin(admin.ModelAdmin):
    form = CarAdminForm

Hope this helps.


如何在Django模板的词典中遍历词典?

问题:如何在Django模板的词典中遍历词典?

我的字典看起来像这样(字典中的字典):

{'0': {
    'chosen_unit': <Unit: Kg>,
    'cost': Decimal('10.0000'),
    'unit__name_abbrev': u'G',
    'supplier__supplier': u"Steve's Meat Locker",
    'price': Decimal('5.00'),
    'supplier__address': u'No\r\naddress here',
    'chosen_unit_amount': u'2',
    'city__name': u'Joburg, Central',
    'supplier__phone_number': u'02299944444',
    'supplier__website': None,
    'supplier__price_list': u'',
    'supplier__email': u'ss.sss@ssssss.com',
    'unit__name': u'Gram',
    'name': u'Rump Bone',
}}

现在,我只是想在模板上显示信息,但是我很挣扎。我的模板代码如下:

{% if landing_dict.ingredients %}
  <hr>
  {% for ingredient in landing_dict.ingredients %}
    {{ ingredient }}
  {% endfor %}
  <a href="/">Print {{ landing_dict.recipe_name }}</a>
{% else %}
  Please search for an ingredient below
{% endif %}

它只是在模板上显示“ 0”?

我也尝试过:

{% for ingredient in landing_dict.ingredients %}
  {{ ingredient.cost }}
{% endfor %}

这甚至不显示结果。

我认为也许我需要更深一层地迭代,所以尝试了一下:

{% if landing_dict.ingredients %}
  <hr>
  {% for ingredient in landing_dict.ingredients %}
    {% for field in ingredient %}
      {{ field }}
    {% endfor %}
  {% endfor %}
  <a href="/">Print {{ landing_dict.recipe_name }}</a>
{% else %}
  Please search for an ingredient below
{% endif %}

但这不会显示任何内容。

我究竟做错了什么?

My dictionary looks like this(Dictionary within a dictionary):

{'0': {
    'chosen_unit': <Unit: Kg>,
    'cost': Decimal('10.0000'),
    'unit__name_abbrev': u'G',
    'supplier__supplier': u"Steve's Meat Locker",
    'price': Decimal('5.00'),
    'supplier__address': u'No\r\naddress here',
    'chosen_unit_amount': u'2',
    'city__name': u'Joburg, Central',
    'supplier__phone_number': u'02299944444',
    'supplier__website': None,
    'supplier__price_list': u'',
    'supplier__email': u'ss.sss@ssssss.com',
    'unit__name': u'Gram',
    'name': u'Rump Bone',
}}

Now I’m just trying to display the information on my template but I’m struggling. My code for the template looks like:

{% if landing_dict.ingredients %}
  <hr>
  {% for ingredient in landing_dict.ingredients %}
    {{ ingredient }}
  {% endfor %}
  <a href="/">Print {{ landing_dict.recipe_name }}</a>
{% else %}
  Please search for an ingredient below
{% endif %}

It just shows me ‘0’ on my template?

I also tried:

{% for ingredient in landing_dict.ingredients %}
  {{ ingredient.cost }}
{% endfor %}

This doesn’t even display a result.

I thought perhaps I need to iterate one level deeper so tried this:

{% if landing_dict.ingredients %}
  <hr>
  {% for ingredient in landing_dict.ingredients %}
    {% for field in ingredient %}
      {{ field }}
    {% endfor %}
  {% endfor %}
  <a href="/">Print {{ landing_dict.recipe_name }}</a>
{% else %}
  Please search for an ingredient below
{% endif %}

But this doesn’t display anything.

What am I doing wrong?


回答 0

可以说您的数据是-

data = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }

您可以使用该data.items()方法来获取字典元素。请注意,在Django模板中,我们不放置()。另外提到的一些用户values[0]不起作用,如果是这种情况,请尝试values.items

<table>
    <tr>
        <td>a</td>
        <td>b</td>
        <td>c</td>
    </tr>

    {% for key, values in data.items %}
    <tr>
        <td>{{key}}</td>
        {% for v in values[0] %}
        <td>{{v}}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>

相当确定您可以将此逻辑扩展到您的特定字典。


要以排序的顺序遍历dict键 -首先,我们在python中排序,然后在django模板中进行迭代和渲染。

return render_to_response('some_page.html', {'data': sorted(data.items())})

在模板文件中:

{% for key, value in data %}
    <tr>
        <td> Key: {{ key }} </td> 
        <td> Value: {{ value }} </td>
    </tr>
{% endfor %}

Lets say your data is –

data = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }

You can use the data.items() method to get the dictionary elements. Note, in django templates we do NOT put (). Also some users mentioned values[0] does not work, if that is the case then try values.items.

<table>
    <tr>
        <td>a</td>
        <td>b</td>
        <td>c</td>
    </tr>

    {% for key, values in data.items %}
    <tr>
        <td>{{key}}</td>
        {% for v in values[0] %}
        <td>{{v}}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>

Am pretty sure you can extend this logic to your specific dict.


To iterate over dict keys in a sorted order – First we sort in python then iterate & render in django template.

return render_to_response('some_page.html', {'data': sorted(data.items())})

In template file:

{% for key, value in data %}
    <tr>
        <td> Key: {{ key }} </td> 
        <td> Value: {{ value }} </td>
    </tr>
{% endfor %}

回答 1

这个答案对我没有用,但是我自己找到了答案。但是,没有人发布我的问题。我懒得先问再回答,所以就把它放在这里。

这用于以下查询:

data = Leaderboard.objects.filter(id=custom_user.id).values(
    'value1',
    'value2',
    'value3')

在模板中:

{% for dictionary in data %}
  {% for key, value in dictionary.items %}
    <p>{{ key }} : {{ value }}</p>
  {% endfor %}
{% endfor %}

This answer didn’t work for me, but I found the answer myself. No one, however, has posted my question. I’m too lazy to ask it and then answer it, so will just put it here.

This is for the following query:

data = Leaderboard.objects.filter(id=custom_user.id).values(
    'value1',
    'value2',
    'value3')

In template:

{% for dictionary in data %}
  {% for key, value in dictionary.items %}
    <p>{{ key }} : {{ value }}</p>
  {% endfor %}
{% endfor %}

回答 2

如果将变量data(字典类型)作为上下文传递给模板,则代码应为:

{% for key, value in data.items %}
    <p>{{ key }} : {{ value }}</p> 
{% endfor %}

If you pass a variable data (dictionary type) as context to a template, then you code should be:

{% for key, value in data.items %}
    <p>{{ key }} : {{ value }}</p> 
{% endfor %}

django模板:包括和扩展

问题:django模板:包括和扩展

我想在2个不同的基本文件中提供相同的内容。

所以我正在尝试这样做:

page1.html:

{% extends "base1.html" %}
{% include "commondata.html" %}

page2.html:

{% extends "base2.html" %} 
{% include "commondata.html" %}

问题是我似乎无法同时使用扩展和包含。有什么办法吗?如果没有,我该如何完成以上工作?

commondata.html覆盖base1.html和base2.html中指定的块

这样做的目的是提供pdf和html格式的同一页面,但格式略有不同。上面的问题虽然简化了我要尝试做的事情,但是如果我可以得到答案,它将解决我的问题。

I would like to provide the same content inside 2 different base files.

So I’m trying to do this:

page1.html:

{% extends "base1.html" %}
{% include "commondata.html" %}

page2.html:

{% extends "base2.html" %} 
{% include "commondata.html" %}

The problem is that I can’t seem to use both extends and include. Is there some way to do that? And if not, how can I accomplish the above?

commondata.html overrides a block that is specified in both base1.html and base2.html

The purpose of this is to provide the same page in both pdf and html format, where the formatting is slightly different. The above question though simplifies what I’m trying to do so if I can get an answer to that it will solve my problem.


回答 0

使用扩展模板标签时,是指当前模板扩展了另一个模板-它是子模板,取决于父模板。Django将查看您的子模板,并使用其内容填充父模板。

您想要在子模板中使用的所有内容都应位于block之内,Django使用该块来填充父模板。如果要在该子模板中使用include语句,则必须将其放在一个块中,以便Django理解。否则,这只是没有意义,而Django不知道该怎么做。

Django文档中有一些非常好的示例,这些示例使用块替换父模板中的块。

https://docs.djangoproject.com/zh-CN/dev/ref/templates/language/#template-inheritance

When you use the extends template tag, you’re saying that the current template extends another — that it is a child template, dependent on a parent template. Django will look at your child template and use its content to populate the parent.

Everything that you want to use in a child template should be within blocks, which Django uses to populate the parent. If you want use an include statement in that child template, you have to put it within a block, for Django to make sense of it. Otherwise it just doesn’t make sense and Django doesn’t know what to do with it.

The Django documentation has a few really good examples of using blocks to replace blocks in the parent template.

https://docs.djangoproject.com/en/dev/ref/templates/language/#template-inheritance


回答 1

从Django文档中:

include标记应被视为“呈现此子模板并包含HTML”的实现,而不应视为“解析此子模板并像其父对象一样包含其内容”。这意味着在包含的模板之间没有共享状态-每个包含都是一个完全独立的呈现过程。

因此,Django不会从您的commondata.html中获取任何块,并且它也不知道如何处理呈现的html外部块。

From Django docs:

The include tag should be considered as an implementation of “render this subtemplate and include the HTML”, not as “parse this subtemplate and include its contents as if it were part of the parent”. This means that there is no shared state between included templates — each include is a completely independent rendering process.

So Django doesn’t grab any blocks from your commondata.html and it doesn’t know what to do with rendered html outside blocks.


回答 2

这应该为您解决了问题:将include标签放在块部分中。

page1.html:

{% extends "base1.html" %}

{% block foo %}
   {% include "commondata.html" %}
{% endblock %}

page2.html:

{% extends "base2.html" %}

{% block bar %}
   {% include "commondata.html" %}
{% endblock %}

This should do the trick for you: put include tag inside of a block section.

page1.html:

{% extends "base1.html" %}

{% block foo %}
   {% include "commondata.html" %}
{% endblock %}

page2.html:

{% extends "base2.html" %}

{% block bar %}
   {% include "commondata.html" %}
{% endblock %}

回答 3

如果它对将来的人有帮助,为什么它对我不起作用的更多信息:

之所以不起作用,是因为django中的{%include%}不喜欢像特殊的撇号这样的特殊字符。我尝试包含的模板数据是从Word粘贴的。我必须手动删除所有这些特殊字符,然后成功包含其中。

More info about why it wasn’t working for me in case it helps future people:

The reason why it wasn’t working is that {% include %} in django doesn’t like special characters like fancy apostrophe. The template data I was trying to include was pasted from word. I had to manually remove all of these special characters and then it included successfully.


回答 4

您不能将包含文件中的块拉入子模板以覆盖父模板的块。但是,您可以在变量中指定父项,并在上下文中指定基本模板。

文档中

{%扩展变量%}使用变量的值。如果该变量的值为字符串,则Django将使用该字符串作为父模板的名称。如果该变量的值为模板对象,则Django将使用该对象作为父模板。

代替单独的“ page1.html”和“ page2.html”,放在“ commondata.html” {% extends base_template %}的顶部。然后在您的视图中,定义base_template为“ base1.html”或“ base2.html”。

You can’t pull in blocks from an included file into a child template to override the parent template’s blocks. However, you can specify a parent in a variable and have the base template specified in the context.

From the documentation:

{% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.

Instead of separate “page1.html” and “page2.html”, put {% extends base_template %} at the top of “commondata.html”. And then in your view, define base_template to be either “base1.html” or “base2.html”.


回答 5

添加以供将来通过Google找到它的人参考:对于此类情况,您可能需要查看夹层库提供的{%overextend%}标签。

Added for reference to future people who find this via google: You might want to look at the {% overextend %} tag provided by the mezzanine library for cases like this.


回答 6

编辑2015年12月10日:正如评论中指出的那样,自1.8版起不推荐使用ssi。根据文档:

该标签已被弃用,并将在Django 1.10中删除。请改用include标签。


在我看来,这个问题的正确答案(最好)是podshumok提出的答案,因为它解释了为什么在与继承一起使用时include的行为。

但是,令我感到有些惊讶的是,没有人提到Django模板系统提供的ssi标记,该标记是专门为内联式设计的,包括一个外部文本。在此,内联表示不会解释,解析或插入外部文本,而只是在调用模板内部“复制”。

请参考文档以获取更多详细信息(请确保在页面右下方的选择器中检查您所使用的Django版本)。

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#ssi

从文档中:

ssi
Outputs the contents of a given file into the page.
Like a simple include tag, {% ssi %} includes the contents of another file
 which must be specified using an absolute path  in the current page

还请注意此技术的安全隐患以及必需的ALLOWED_INCLUDE_ROOTS定义,必须将其添加到设置文件中。

Edit 10th Dec 2015: As pointed out in the comments, ssi is deprecated since version 1.8. According to the documentation:

This tag has been deprecated and will be removed in Django 1.10. Use the include tag instead.


In my opinion, the right (best) answer to this question is the one from podshumok, as it explains why the behaviour of include when used along with inheritance.

However, I was somewhat surprised that nobody mentioned the ssi tag provided by the Django templating system, which is specifically designed for inline including an external piece of text. Here, inline means the external text will not be interpreted, parsed or interpolated, but simply “copied” inside the calling template.

Please, refer to the documentation for further details (be sure to check your appropriate version of Django in the selector at the lower right part of the page).

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#ssi

From the documentation:

ssi
Outputs the contents of a given file into the page.
Like a simple include tag, {% ssi %} includes the contents of another file
– which must be specified using an absolute path – in the current page

Beware also of the security implications of this technique and also of the required ALLOWED_INCLUDE_ROOTS define, which must be added to your settings files.


在Django模板中按索引引用列表项?

问题:在Django模板中按索引引用列表项?

这可能很简单,但是我环顾四周,找不到答案。从Django模板引用列表中的单个项目的最佳方法是什么?

换句话说,{{ data[0] }}在模板语言中我该如何做?

谢谢。

This may be simple, but I looked around and couldn’t find an answer. What’s the best way to reference a single item in a list from a Django template?

In other words how do I do the equivalent of {{ data[0] }} within the template language?

Thanks.


回答 0

看起来像{{ data.0 }}。请参阅变量和查找

It looks like {{ data.0 }}. See Variables and lookups.


回答 1

更好的方法:自定义模板过滤器:https : //docs.djangoproject.com/en/dev/howto/custom-template-tags/

例如在模板中获取my_list [x]:

在模板中

{% load index %}
{{ my_list|index:x }}

templatetags / index.py

from django import template
register = template.Library()

@register.filter
def index(indexable, i):
    return indexable[i]

如果my_list = [['a','b','c'], ['d','e','f']],您可以{{ my_list|index:x|index:y }}在模板中使用my_list[x][y]

与“ for”一起正常工作

{{ my_list|index:forloop.counter0 }}

经过测试,效果很好^ _ ^

A better way: custom template filter: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

such as get my_list[x] in templates:

in template

{% load index %}
{{ my_list|index:x }}

templatetags/index.py

from django import template
register = template.Library()

@register.filter
def index(indexable, i):
    return indexable[i]

if my_list = [['a','b','c'], ['d','e','f']], you can use {{ my_list|index:x|index:y }} in template to get my_list[x][y]

It works fine with “for”

{{ my_list|index:forloop.counter0 }}

Tested and works well ^_^


回答 2

{{ data.0 }} 应该管用。

假设您写了data.objdjango try data.objdata.obj()。如果他们不起作用,它会尝试data["obj"]。你的情况data[0]可以写成{{ data.0 }}。但是我建议您data[0]插入视图并将其作为单独的变量发送。

{{ data.0 }} should work.

Let’s say you wrote data.obj django tries data.obj and data.obj(). If they don’t work it tries data["obj"]. In your case data[0] can be written as {{ data.0 }}. But I recommend you to pull data[0] in the view and send it as separate variable.


回答 3

@ jennifer06262016,您绝对可以添加另一个过滤器以返回Django Queryset中的对象。

@register.filter 
def get_item(Queryset):
    return Queryset.your_item_key

在这种情况下,您可以在模板中输入类似{{Queryset | index:x | get_item}}的内容,以访问某些字典对象。这个对我有用。

@jennifer06262016, you can definitely add another filter to return the objects inside a django Queryset.

@register.filter 
def get_item(Queryset):
    return Queryset.your_item_key

In that case, you would type something like this {{ Queryset|index:x|get_item }} into your template to access some dictionary object. It works for me.


Django,创建自定义500/404错误页面

问题:Django,创建自定义500/404错误页面

完全按照此处找到的教程进行操作,我无法创建自定义的500或404错误页面。如果我确实输入了错误的网址,则该页面会显示默认的错误页面。我应该检查哪些内容以防止显示自定义页面?

文件目录:

mysite/
    mysite/
        __init__.py
        __init__.pyc
        settings.py
        settings.pyc
        urls.py
        urls.pyc
        wsgi.py
        wsgi.pyc
    polls/
        templates/
            admin/
                base_site.html
            404.html
            500.html
            polls/
                detail.html
                index.html
        __init__.py
        __init__.pyc
        admin.py
        admin.pyc
        models.py
        models.pyc
        tests.py
        urls.py
        urls.pyc
        view.py
        views.pyc
    templates/
    manage.py

在mysite / settings.py中,我启用了以下功能:

DEBUG = False
TEMPLATE_DEBUG = DEBUG

#....

TEMPLATE_DIRS = (
    'C:/Users/Me/Django/mysite/templates', 
)

在mysite / polls / urls.py中:

from django.conf.urls import patterns, url

from polls import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
    url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
    url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)

我可以发布任何其他必要的代码,但是如果我使用了错误的网址,应该如何更改以获得自定义500错误页面?

编辑

解决方案: 我还有一个

TEMPLATE_DIRS

在我的settings.py中,那是导致问题的原因

Following the tutorial found here exactly, I cannot create a custom 500 or 404 error page. If I do type in a bad url, the page gives me the default error page. Is there anything I should be checking for that would prevent a custom page from showing up?

File directories:

mysite/
    mysite/
        __init__.py
        __init__.pyc
        settings.py
        settings.pyc
        urls.py
        urls.pyc
        wsgi.py
        wsgi.pyc
    polls/
        templates/
            admin/
                base_site.html
            404.html
            500.html
            polls/
                detail.html
                index.html
        __init__.py
        __init__.pyc
        admin.py
        admin.pyc
        models.py
        models.pyc
        tests.py
        urls.py
        urls.pyc
        view.py
        views.pyc
    templates/
    manage.py

within mysite/settings.py I have these enabled:

DEBUG = False
TEMPLATE_DEBUG = DEBUG

#....

TEMPLATE_DIRS = (
    'C:/Users/Me/Django/mysite/templates', 
)

within mysite/polls/urls.py:

from django.conf.urls import patterns, url

from polls import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
    url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
    url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)

I can post any other code necessary, but what should I be changing to get a custom 500 error page if I use a bad url?

Edit

SOLUTION: I had an additional

TEMPLATE_DIRS

within my settings.py and that was causing the problem


回答 0

在您的主目录下,views.py添加您自己的以下两个视图的自定义实现,然后只需设置要显示的模板404.html500.html

使用此解决方案,无需将自定义代码添加到 urls.py

这是代码:

from django.shortcuts import render_to_response
from django.template import RequestContext


def handler404(request, *args, **argv):
    response = render_to_response('404.html', {},
                                  context_instance=RequestContext(request))
    response.status_code = 404
    return response


def handler500(request, *args, **argv):
    response = render_to_response('500.html', {},
                                  context_instance=RequestContext(request))
    response.status_code = 500
    return response

更新资料

handler404handler500导出的Django字符串配置变量django/conf/urls/__init__.py。这就是上面的配置起作用的原因。

为了使上述配置生效,您应该在urls.py文件中定义以下变量,并将导出的Django变量指向定义这些Django功能视图的字符串Python路径,如下所示:

# project/urls.py

handler404 = 'my_app.views.handler404'
handler500 = 'my_app.views.handler500'

Django 2.0更新

处理程序视图的签名在Django 2.0中已更改:https : //docs.djangoproject.com/en/2.0/ref/views/#error-views

如果您使用上述视图,则handler404将失败并显示以下消息:

“ handler404()获得了意外的关键字参数’exception’”

在这种情况下,请修改您的视图,如下所示:

def handler404(request, exception, template_name="404.html"):
    response = render_to_response(template_name)
    response.status_code = 404
    return response

Under your main views.py add your own custom implementation of the following two views, and just set up the templates 404.html and 500.html with what you want to display.

With this solution, no custom code needs to be added to urls.py

Here’s the code:

from django.shortcuts import render_to_response
from django.template import RequestContext


def handler404(request, *args, **argv):
    response = render_to_response('404.html', {},
                                  context_instance=RequestContext(request))
    response.status_code = 404
    return response


def handler500(request, *args, **argv):
    response = render_to_response('500.html', {},
                                  context_instance=RequestContext(request))
    response.status_code = 500
    return response

Update

handler404 and handler500 are exported Django string configuration variables found in django/conf/urls/__init__.py. That is why the above config works.

To get the above config to work, you should define the following variables in your urls.py file and point the exported Django variables to the string Python path of where these Django functional views are defined, like so:

# project/urls.py

handler404 = 'my_app.views.handler404'
handler500 = 'my_app.views.handler500'

Update for Django 2.0

Signatures for handler views were changed in Django 2.0: https://docs.djangoproject.com/en/2.0/ref/views/#error-views

If you use views as above, handler404 will fail with message:

“handler404() got an unexpected keyword argument ‘exception'”

In such case modify your views like this:

def handler404(request, exception, template_name="404.html"):
    response = render_to_response(template_name)
    response.status_code = 404
    return response

回答 1

官方回答:

这是有关如何设置自定义错误视图的官方文档的链接:

https://docs.djangoproject.com/zh-CN/stable/topics/http/views/#customizing-error-views

它说在URLconf中添加这样的行(在其他任何地方设置它们都无效):

handler404 = 'mysite.views.my_custom_page_not_found_view'
handler500 = 'mysite.views.my_custom_error_view'
handler403 = 'mysite.views.my_custom_permission_denied_view'
handler400 = 'mysite.views.my_custom_bad_request_view'

您还可以通过修改设置来自定义CSRF错误视图CSRF_FAILURE_VIEW

默认错误处理程序:

这是值得一读的默认错误处理程序的文档page_not_foundserver_errorpermission_deniedbad_request。默认情况下,他们使用这些模板,如果他们可以分别找到他们,: ,404.html500.html403.html400.html

因此,如果您要做的只是创建漂亮的错误页面,只需在TEMPLATE_DIRS目录中创建这些文件,则根本不需要编辑URLConf。阅读文档以查看可用的上下文变量。

在Django 1.10及更高版本中,默认的CSRF错误视图使用template 403_csrf.html

陷阱:

不要忘记DEBUG必须将它们设置为False才能起作用,否则,将使用常规的调试处理程序。

Official answer:

Here is the link to the official documentation on how to set up custom error views:

https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views

It says to add lines like these in your URLconf (setting them anywhere else will have no effect):

handler404 = 'mysite.views.my_custom_page_not_found_view'
handler500 = 'mysite.views.my_custom_error_view'
handler403 = 'mysite.views.my_custom_permission_denied_view'
handler400 = 'mysite.views.my_custom_bad_request_view'

You can also customise the CSRF error view by modifying the setting CSRF_FAILURE_VIEW.

Default error handlers:

It’s worth reading the documentation of the default error handlers, page_not_found, server_error, permission_denied and bad_request. By default, they use these templates if they can find them, respectively: 404.html, 500.html, 403.html, and 400.html.

So if all you want to do is make pretty error pages, just create those files in a TEMPLATE_DIRS directory, you don’t need to edit URLConf at all. Read the documentation to see which context variables are available.

In Django 1.10 and later, the default CSRF error view uses the template 403_csrf.html.

Gotcha:

Don’t forget that DEBUG must be set to False for these to work, otherwise, the normal debug handlers will be used.


回答 2

将这些行添加到urls.py中

urls.py

from django.conf.urls import (
handler400, handler403, handler404, handler500
)

handler400 = 'my_app.views.bad_request'
handler403 = 'my_app.views.permission_denied'
handler404 = 'my_app.views.page_not_found'
handler500 = 'my_app.views.server_error'

# ...

并在views.py中实现我们的自定义视图。

views.py

from django.shortcuts import (
render_to_response
)
from django.template import RequestContext

# HTTP Error 400
def bad_request(request):
    response = render_to_response(
        '400.html',
        context_instance=RequestContext(request)
        )

        response.status_code = 400

        return response

# ...

Add these lines in urls.py

urls.py

from django.conf.urls import (
handler400, handler403, handler404, handler500
)

handler400 = 'my_app.views.bad_request'
handler403 = 'my_app.views.permission_denied'
handler404 = 'my_app.views.page_not_found'
handler500 = 'my_app.views.server_error'

# ...

and implement our custom views in views.py.

views.py

from django.shortcuts import (
render_to_response
)
from django.template import RequestContext

# HTTP Error 400
def bad_request(request):
    response = render_to_response(
        '400.html',
        context_instance=RequestContext(request)
        )

        response.status_code = 400

        return response

# ...

回答 3

从您引用的页面:

当您从视图中引发Http404时,Django将加载一个专用于处理404错误的特殊视图。它通过在根URLconf中(仅在根URLconf中;在其他任何位置设置handler404都无效)中查找变量handler404来找到它,这是Python点分语法的字符串–与普通URLconf回调使用的格式相同。404视图本身没有什么特别的:它只是一个普通视图。

因此,我相信您需要在urls.py中添加以下内容:

handler404 = 'views.my_404_view'

和handler500类似。

From the page you referenced:

When you raise Http404 from within a view, Django will load a special view devoted to handling 404 errors. It finds it by looking for the variable handler404 in your root URLconf (and only in your root URLconf; setting handler404 anywhere else will have no effect), which is a string in Python dotted syntax – the same format the normal URLconf callbacks use. A 404 view itself has nothing special: It’s just a normal view.

So I believe you need to add something like this to your urls.py:

handler404 = 'views.my_404_view'

and similar for handler500.


回答 4

如果您需要的是在时显示自定义页面,其中包含您网站的一些错误消息DEBUG = False,则在模板目录中添加两个名为404.html和500.html的模板,当404或500时,它将自动提取此自定义页面被提出。

If all you need is to show custom pages which have some fancy error messages for your site when DEBUG = False, then add two templates named 404.html and 500.html in your templates directory and it will automatically pick up this custom pages when a 404 or 500 is raised.


回答 5

Django 2. *中,您可以在views.py中使用此构造

def handler404(request, exception):
    return render(request, 'errors/404.html', locals())

settings.py中

DEBUG = False

if DEBUG is False:
    ALLOWED_HOSTS = [
        '127.0.0.1:8000',
        '*',
    ]

if DEBUG is True:
    ALLOWED_HOSTS = []

urls.py中

# https://docs.djangoproject.com/en/2.0/topics/http/views/#customizing-error-views
handler404 = 'YOUR_APP_NAME.views.handler404'

通常我创建default_app并处理站点范围的错误,并在其中处理上下文。

In Django 2.* you can use this construction in views.py

def handler404(request, exception):
    return render(request, 'errors/404.html', locals())

In settings.py

DEBUG = False

if DEBUG is False:
    ALLOWED_HOSTS = [
        '127.0.0.1:8000',
        '*',
    ]

if DEBUG is True:
    ALLOWED_HOSTS = []

In urls.py

# https://docs.djangoproject.com/en/2.0/topics/http/views/#customizing-error-views
handler404 = 'YOUR_APP_NAME.views.handler404'

Usually i creating default_app and handle site-wide errors, context processors in it.


回答 6

settings.py:

DEBUG = False
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = ['localhost']  #provide your host name

并将您的404.html500.html页面添加到模板文件夹中。删除404.html500.html从模板中投票应用程序。

settings.py:

DEBUG = False
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = ['localhost']  #provide your host name

and just add your 404.html and 500.html pages in templates folder. remove 404.html and 500.html from templates in polls app.


回答 7

出错,在错误页面上找到django从何处加载模板。我的意思是路径堆栈。在基本template_dir中添加这些html页面500.html404.html。发生这些错误时,将自动加载相应的模板文件。

您也可以为其他错误代码添加页面,例如400403

希望这个帮助!

Make an error, On the error page find out from where django is loading templates.I mean the path stack.In base template_dir add these html pages 500.html , 404.html. When these errors occur the respective template files will be automatically loaded.

You can add pages for other error codes too, like 400 and 403.

Hope this help !!!


回答 8

在Django中3.x,接受的答案将不起作用,因为render_to_response自从接受的版本适用于该版本以来,它已被完全删除以及进行了一些其他更改。

还有其他一些答案,但我提供的答案更简洁:

在您的主urls.py文件中:

handler404 = 'yourapp.views.handler404'
handler500 = 'yourapp.views.handler500'

yourapp/views.py文件中:

def handler404(request, exception):
    context = {}
    response = render(request, "pages/errors/404.html", context=context)
    response.status_code = 404
    return response


def handler500(request):
    context = {}
    response = render(request, "pages/errors/500.html", context=context)
    response.status_code = 500
    return response

请确保您已导入render()yourapp/views.py文件:

from django.shortcuts import render

旁注:render_to_response()在Django中已弃用,2.x在verision中已完全删除3.x

In Django 3.x, the accepted answer won’t work because render_to_response has been removed completely as well as some more changes have been made since the version the accepted answer worked for.

Some other answers are also there but I’m presenting a little cleaner answer:

In your main urls.py file:

handler404 = 'yourapp.views.handler404'
handler500 = 'yourapp.views.handler500'

In yourapp/views.py file:

def handler404(request, exception):
    context = {}
    response = render(request, "pages/errors/404.html", context=context)
    response.status_code = 404
    return response


def handler500(request):
    context = {}
    response = render(request, "pages/errors/500.html", context=context)
    response.status_code = 500
    return response

Ensure that you have imported render() in yourapp/views.py file:

from django.shortcuts import render

Side note: render_to_response() was deprecated in Django 2.x and it has been completely removed in verision 3.x.


回答 9

作为一行(对于404通用页面):

from django.shortcuts import render_to_response
from django.template import RequestContext

return render_to_response('error/404.html', {'exception': ex},
                                      context_instance=RequestContext(request), status=404)

As one single line (for 404 generic page):

from django.shortcuts import render_to_response
from django.template import RequestContext

return render_to_response('error/404.html', {'exception': ex},
                                      context_instance=RequestContext(request), status=404)

回答 10

# views.py
def handler404(request, exception):
    context = RequestContext(request)
    err_code = 404
    response = render_to_response('404.html', {"code":err_code}, context)
    response.status_code = 404
    return response

# <project_folder>.urls.py
handler404 = 'todo.views.handler404' 

这适用于Django 2.0

确保将您的自定义内容404.html包含在应用程序模板文件夹中。

# views.py
def handler404(request, exception):
    context = RequestContext(request)
    err_code = 404
    response = render_to_response('404.html', {"code":err_code}, context)
    response.status_code = 404
    return response

# <project_folder>.urls.py
handler404 = 'todo.views.handler404' 

This works on django 2.0

Be sure to include your custom 404.html inside the app templates folder.


回答 11

Django 3.0

这是链接如何自定义错误视图

这是链接如何渲染视图

urls.py(主文件夹中的项目文件夹中)中,放入:

handler404 = 'my_app_name.views.custom_page_not_found_view'
handler500 = 'my_app_name.views.custom_error_view'
handler403 = 'my_app_name.views.custom_permission_denied_view'
handler400 = 'my_app_name.views.custom_bad_request_view'

并在该应用(my_app_name)中放入views.py

def custom_page_not_found_view(request, exception):
    return render(request, "errors/404.html", {})

def custom_error_view(request, exception=None):
    return render(request, "errors/500.html", {})

def custom_permission_denied_view(request, exception=None):
    return render(request, "errors/403.html", {})

def custom_bad_request_view(request, exception=None):
    return render(request, "errors/400.html", {})

注意:error/404.html如果您将文件放置到项目(而不是应用程序)模板文件夹中templates/errors/404.html,则为路径,因此请将文件放置在所需位置并编写正确的路径。

注2:页面重新加载后,如果仍然看到旧模板,请更改settings.py DEBUG=True,保存它,然后再次更改为False(重新启动服务器并收集新文件)。

Django 3.0

here is link how to customize error views

here is link how to render a view

in the urls.py (the main one, in project folder), put:

handler404 = 'my_app_name.views.custom_page_not_found_view'
handler500 = 'my_app_name.views.custom_error_view'
handler403 = 'my_app_name.views.custom_permission_denied_view'
handler400 = 'my_app_name.views.custom_bad_request_view'

and in that app (my_app_name) put in the views.py:

def custom_page_not_found_view(request, exception):
    return render(request, "errors/404.html", {})

def custom_error_view(request, exception=None):
    return render(request, "errors/500.html", {})

def custom_permission_denied_view(request, exception=None):
    return render(request, "errors/403.html", {})

def custom_bad_request_view(request, exception=None):
    return render(request, "errors/400.html", {})

NOTE: error/404.html is the path if you place your files into the projects (not the apps) template foldertemplates/errors/404.html so please place the files where you want and write the right path.

NOTE 2: After page reload, if you still see the old template, change in settings.py DEBUG=True, save it, and then again to False (to restart the server and collect the new files).


回答 12

不需要其他视图。https://docs.djangoproject.com/zh-CN/3.0/ref/views/

只需将错误文件放在模板目录的根目录中

  • 404.html
  • 400.html
  • 403.html
  • 500.html

当debug为False时,它应该使用您的错误页面

No additional view is required. https://docs.djangoproject.com/en/3.0/ref/views/

Just put the error files in the root of templates directory

  • 404.html
  • 400.html
  • 403.html
  • 500.html

And it should use your error page when debug is False


回答 13

尝试将错误模板移至.../Django/mysite/templates/

我注意到这一点,但是我认为这些对于网站来说必须是“全球性的”。

Try moving your error templates to .../Django/mysite/templates/ ?

I’m note sure about this one, but i think these need to be “global” to the website.


如何在Django模板中进行数学运算?

问题:如何在Django模板中进行数学运算?

我想做这个:

100 - {{ object.article.rating_score }} 

因此,例如,输出将是20,如果{{ object.article.rating_score }}追平80

如何在模板级别执行此操作?我无权访问Python代码。

I want to do this:

100 - {{ object.article.rating_score }} 

So for example, the output would be 20 if {{ object.article.rating_score }} equaled 80.

How do I do this at the template level? I don’t have access to the Python code.


回答 0

您可以使用add过滤器:

{{ object.article.rating_score|add:"-100" }}

You can use the add filter:

{{ object.article.rating_score|add:"-100" }}

回答 1

使用django-mathfilters。除了内置的添加过滤器外,它还提供了过滤器以减去,相乘,除以和取绝对值。

对于上面的特定示例,您可以使用{{ 100|sub:object.article.rating_score }}

Use django-mathfilters. In addition to the built-in add filter, it provides filters to subtract, multiply, divide, and take the absolute value.

For the specific example above, you would use {{ 100|sub:object.article.rating_score }}.


回答 2

通常,建议您在视图中进行此计算。否则,您可以使用添加过滤器。

Generally it is recommended you do this calculation in your view. Otherwise, you could use the add filter.


在没有其他Django的情况下如何使用Django模板?

问题:在没有其他Django的情况下如何使用Django模板?

我想在我的(Python)代码中使用Django模板引擎,但是我没有构建基于Django的网站。如何在没有settings.py文件(和其他文件)且没有设置DJANGO_SETTINGS_MODULE环境变量的情况下使用它?

如果我运行以下代码:

>>> import django.template
>>> from django.template import Template, Context
>>> t = Template('My name is {{ my_name }}.')

我得到:

ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

I want to use the Django template engine in my (Python) code, but I’m not building a Django-based web site. How do I use it without having a settings.py file (and others) and having to set the DJANGO_SETTINGS_MODULE environment variable?

If I run the following code:

>>> import django.template
>>> from django.template import Template, Context
>>> t = Template('My name is {{ my_name }}.')

I get:

ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

回答 0

解决方案很简单。它实际上有据可查,但不太容易找到。(我必须仔细研究-当我尝试了几种其他的Google搜索时并没有出现。)

以下代码有效:

>>> from django.template import Template, Context
>>> from django.conf import settings
>>> settings.configure()
>>> t = Template('My name is {{ my_name }}.')
>>> c = Context({'my_name': 'Daryl Spitzer'})
>>> t.render(c)
u'My name is Daryl Spitzer.'

有关您可能要定义的某些设置(作为要配置的关键字参数)的说明,请参阅Django文档(上文链接)。

The solution is simple. It’s actually well documented, but not too easy to find. (I had to dig around — it didn’t come up when I tried a few different Google searches.)

The following code works:

>>> from django.template import Template, Context
>>> from django.conf import settings
>>> settings.configure()
>>> t = Template('My name is {{ my_name }}.')
>>> c = Context({'my_name': 'Daryl Spitzer'})
>>> t.render(c)
u'My name is Daryl Spitzer.'

See the Django documentation (linked above) for a description of some of the settings you may want to define (as keyword arguments to configure).


回答 1

Jinja2 语法与Django几乎相同,只是差别很小,而且您获得了功能更强大的模板引擎,该引擎还将模板编译为字节码(FAST!)。

我使用它来进行模板化,包括在Django本身中,它非常好。如果缺少某些所需功能,您也可以轻松编写扩展名。

这是代码生成的一些演示:

>>> import jinja2
>>> print jinja2.Environment().compile('{% for row in data %}{{ row.name | upper }}{% endfor %}', raw=True) 
from __future__ import division
from jinja2.runtime import LoopContext, Context, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_join
name = None

def root(context, environment=environment):
    l_data = context.resolve('data')
    t_1 = environment.filters['upper']
    if 0: yield None
    for l_row in l_data:
        if 0: yield None
        yield unicode(t_1(environment.getattr(l_row, 'name')))

blocks = {}
debug_info = '1=9'

Jinja2 syntax is pretty much the same as Django’s with very few differences, and you get a much more powerfull template engine, which also compiles your template to bytecode (FAST!).

I use it for templating, including in Django itself, and it is very good. You can also easily write extensions if some feature you want is missing.

Here is some demonstration of the code generation:

>>> import jinja2
>>> print jinja2.Environment().compile('{% for row in data %}{{ row.name | upper }}{% endfor %}', raw=True) 
from __future__ import division
from jinja2.runtime import LoopContext, Context, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_join
name = None

def root(context, environment=environment):
    l_data = context.resolve('data')
    t_1 = environment.filters['upper']
    if 0: yield None
    for l_row in l_data:
        if 0: yield None
        yield unicode(t_1(environment.getattr(l_row, 'name')))

blocks = {}
debug_info = '1=9'

回答 2

您要使用Django模板的任何特殊原因?无论神社元史是,在我看来,优越。


如果您确实愿意,请参见中的Django文档settings.py。特别是“使用设置而不设置DJANGO_SETTINGS_MODULE”部分。使用这样的东西:

from django.conf import settings
settings.configure (FOO='bar') # Your settings go here

Any particular reason you want to use Django’s templates? Both Jinja and Genshi are, in my opinion, superior.


If you really want to, then see the Django documentation on settings.py. Especially the section “Using settings without setting DJANGO_SETTINGS_MODULE“. Use something like this:

from django.conf import settings
settings.configure (FOO='bar') # Your settings go here

回答 3

我还建议jinja2。关于vs. 有一篇不错的文章,其中提供了一些详细信息,说明您为什么偏爱后者。djangojinja2

I would also recommend jinja2. There is a nice article on django vs. jinja2 that gives some in-detail information on why you should prefere the later.


回答 4

根据Jinja文档,Python 3支持仍处于试验阶段。因此,如果您使用的是Python 3,而性能不是问题,则可以使用django的内置模板引擎。

Django 1.8引入了对多个模板引擎的支持,这需要更改模板的初始化方式。您必须显式配置settings.DEBUGdjango提供的默认模板引擎使用的模板。这是不使用django其余部分即可使用模板的代码。

from django.template import Template, Context
from django.template.engine import Engine

from django.conf import settings
settings.configure(DEBUG=False)

template_string = "Hello {{ name }}"
template = Template(template_string, engine=Engine())
context = Context({"name": "world"})
output = template.render(context) #"hello world"

According to the Jinja documentation, Python 3 support is still experimental. So if you are on Python 3 and performance is not an issue, you can use django’s built in template engine.

Django 1.8 introduced support for multiple template engines which requires a change to the way templates are initialized. You have to explicitly configure settings.DEBUG which is used by the default template engine provided by django. Here’s the code to use templates without using the rest of django.

from django.template import Template, Context
from django.template.engine import Engine

from django.conf import settings
settings.configure(DEBUG=False)

template_string = "Hello {{ name }}"
template = Template(template_string, engine=Engine())
context = Context({"name": "world"})
output = template.render(context) #"hello world"

回答 5

除了其他人写的东西之外,如果要在Django> 1.7上使用Django模板,则必须给您的settings.configure(…)调用TEMPLATES变量,然后像这样调用django.setup():

from django.conf import settings

settings.configure(TEMPLATES=[
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['.'], # if you want the templates from a file
        'APP_DIRS': False, # we have no apps
    },
])

import django
django.setup()

然后,您可以像通常一样从字符串加载模板:

from django import template   
t = template.Template('My name is {{ name }}.')   
c = template.Context({'name': 'Rob'})   
t.render(c)

而且,如果您在磁盘中的.configure中写入了DIRS变量,则:

from django.template.loader import get_template
t = get_template('a.html')
t.render({'name': 5})

Django错误:未配置DjangoTemplates后端

http://django.readthedocs.io/zh-CN/latest/releases/1.7.html#standalone-scripts

An addition to what other wrote, if you want to use Django Template on Django > 1.7, you must give your settings.configure(…) call the TEMPLATES variable and call django.setup() like this :

from django.conf import settings

settings.configure(TEMPLATES=[
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['.'], # if you want the templates from a file
        'APP_DIRS': False, # we have no apps
    },
])

import django
django.setup()

Then you can load your template like normally, from a string :

from django import template   
t = template.Template('My name is {{ name }}.')   
c = template.Context({'name': 'Rob'})   
t.render(c)

And if you wrote the DIRS variable in the .configure, from the disk :

from django.template.loader import get_template
t = get_template('a.html')
t.render({'name': 5})

Django Error: No DjangoTemplates backend is configured

http://django.readthedocs.io/en/latest/releases/1.7.html#standalone-scripts


回答 6

我也会说Jinja。它绝对比Django Templating Engine 更强大,并且是独立的

如果这是现有Django应用程序的外部插件,则可以创建一个自定义命令,并在项目环境中使用模板引擎。像这样;

manage.py generatereports --format=html

但是我认为仅仅使用Django模板引擎而不是Jinja是不值得的。

I would say Jinja as well. It is definitely more powerful than Django Templating Engine and it is stand alone.

If this was an external plug to an existing Django application, you could create a custom command and use the templating engine within your projects environment. Like this;

manage.py generatereports --format=html

But I don’t think it is worth just using the Django Templating Engine instead of Jinja.


回答 7

谢谢大家的帮助。这是另外一个。您需要使用自定义模板标签的情况。

假设您在read.py模块中有这个重要的模板标签

from django import template

register = template.Library()

@register.filter(name='bracewrap')
def bracewrap(value):
    return "{" + value + "}"

这是html模板文件“ temp.html”:

{{var|bracewrap}}

最后,这是一个将所有内容捆绑在一起的Python脚本

import django
from django.conf import settings
from django.template import Template, Context
import os

#load your tags
from django.template.loader import get_template
django.template.base.add_to_builtins("read")

# You need to configure Django a bit
settings.configure(
    TEMPLATE_DIRS=(os.path.dirname(os.path.realpath(__file__)), ),
)

#or it could be in python
#t = Template('My name is {{ my_name }}.')
c = Context({'var': 'stackoverflow.com rox'})

template = get_template("temp.html")
# Prepare context ....
print template.render(c)

输出将是

{stackoverflow.com rox}

Thanks for the help folks. Here is one more addition. The case where you need to use custom template tags.

Let’s say you have this important template tag in the module read.py

from django import template

register = template.Library()

@register.filter(name='bracewrap')
def bracewrap(value):
    return "{" + value + "}"

This is the html template file “temp.html”:

{{var|bracewrap}}

Finally, here is a Python script that will tie to all together

import django
from django.conf import settings
from django.template import Template, Context
import os

#load your tags
from django.template.loader import get_template
django.template.base.add_to_builtins("read")

# You need to configure Django a bit
settings.configure(
    TEMPLATE_DIRS=(os.path.dirname(os.path.realpath(__file__)), ),
)

#or it could be in python
#t = Template('My name is {{ my_name }}.')
c = Context({'var': 'stackoverflow.com rox'})

template = get_template("temp.html")
# Prepare context ....
print template.render(c)

The output would be

{stackoverflow.com rox}

回答 8


回答 9

别。改用StringTemplate-一旦知道它,就没有理由考虑其他模板引擎了。

Don’t. Use StringTemplate instead–there is no reason to consider any other template engine once you know about it.


回答 10

我回应以上陈述。Jinja 2是通用模板的一个很好的Django模板超集。我认为他们正在努力使Django模板与settings.py的耦合度降低一些,但是Jinja应该为您做的更好。

I echo the above statements. Jinja 2 is a pretty good superset of Django templates for general use. I think they’re working on making the Django templates a little less coupled to the settings.py, but Jinja should do well for you.


回答 11

运行manage.py外壳程序时:

>>> from django import template   
>>> t = template.Template('My name is {{ me }}.')   
>>> c = template.Context({'me': 'ShuJi'})   
>>> t.render(c)

While running the manage.py shell:

>>> from django import template   
>>> t = template.Template('My name is {{ me }}.')   
>>> c = template.Context({'me': 'ShuJi'})   
>>> t.render(c)

回答 12

Google AppEngine使用Django模板引擎,您是否看过它们的工作方式?您可以使用它。

Google AppEngine uses the Django templating engine, have you taken a look at how they do it? You could possibly just use that.


django模板中的“ none”是什么意思?

问题:django模板中的“ none”是什么意思?

我想看看Django模板中是否没有字段/变量。正确的语法是什么?

这是我目前拥有的:

{% if profile.user.first_name is null %}
  <p> -- </p>
{% elif %}
  {{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif%}

在上面的示例中,我将用什么来替换“空”?

I want to see if a field/variable is none within a Django template. What is the correct syntax for that?

This is what I currently have:

{% if profile.user.first_name is null %}
  <p> -- </p>
{% elif %}
  {{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif%}

In the example above, what would I use to replace “null”?


回答 0

None, False and True所有这些都可在模板标记和过滤器中找到。None, False,空字符串('', "", """""")和空列表/元组False都由进行求值if,因此您可以轻松地执行

{% if profile.user.first_name == None %}
{% if not profile.user.first_name %}

提示:@fabiocerqueira是正确的,将逻辑留给模型,将模板限制为唯一的表示层,并计算模型中的内容。一个例子:

# someapp/models.py
class UserProfile(models.Model):
    user = models.OneToOneField('auth.User')
    # other fields

    def get_full_name(self):
        if not self.user.first_name:
            return
        return ' '.join([self.user.first_name, self.user.last_name])

# template
{{ user.get_profile.get_full_name }}

希望这可以帮助 :)

None, False and True all are available within template tags and filters. None, False, the empty string ('', "", """""") and empty lists/tuples all evaluate to False when evaluated by if, so you can easily do

{% if profile.user.first_name == None %}
{% if not profile.user.first_name %}

A hint: @fabiocerqueira is right, leave logic to models, limit templates to be the only presentation layer and calculate stuff like that in you model. An example:

# someapp/models.py
class UserProfile(models.Model):
    user = models.OneToOneField('auth.User')
    # other fields

    def get_full_name(self):
        if not self.user.first_name:
            return
        return ' '.join([self.user.first_name, self.user.last_name])

# template
{{ user.get_profile.get_full_name }}

Hope this helps :)


回答 1

您还可以使用其他内置模板 default_if_none

{{ profile.user.first_name|default_if_none:"--" }}

You can also use another built-in template default_if_none

{{ profile.user.first_name|default_if_none:"--" }}

回答 2

is运算符:Django 1.10中的新增功能

{% if somevar is None %}
  This appears if somevar is None, or if somevar is not found in the context.
{% endif %}

isoperator : New in Django 1.10

{% if somevar is None %}
  This appears if somevar is None, or if somevar is not found in the context.
{% endif %}

回答 3

看看yesno助手

例如:

{{ myValue|yesno:"itwasTrue,itWasFalse,itWasNone" }}

Look at the yesno helper

Eg:

{{ myValue|yesno:"itwasTrue,itWasFalse,itWasNone" }}

回答 4

{% if profile.user.first_name %}起作用(假设您也不想接受'')。

if在Python一般对待NoneFalse''[]{},…所有为假。

{% if profile.user.first_name %} works (assuming you also don’t want to accept '').

if in Python in general treats None, False, '', [], {}, … all as false.


回答 5

您还可以使用内置的模板过滤器default

如果value的值为False(例如None,一个空字符串,0,False);默认显示为“-”。

{{ profile.user.first_name|default:"--" }}

文档:https : //docs.djangoproject.com/en/dev/ref/templates/builtins/#default

You can also use the built-in template filter default:

If value evaluates to False (e.g. None, an empty string, 0, False); the default “–” is displayed.

{{ profile.user.first_name|default:"--" }}

Documentation: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#default


回答 6

您可以尝试以下方法:

{% if not profile.user.first_name.value %}
  <p> -- </p>
{% else %}
  {{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif %}

这样,您实际上是在检查表单字段first_name是否具有与其关联的任何值。见{{ field.value }}循环遍历Django文档形式的领域

我正在使用Django 3.0。

You could try this:

{% if not profile.user.first_name.value %}
  <p> -- </p>
{% else %}
  {{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif %}

This way, you’re essentially checking to see if the form field first_name has any value associated with it. See {{ field.value }} in Looping over the form’s fields in Django Documentation.

I’m using Django 3.0.


如何在Django模板中获取网站的域名?

问题:如何在Django模板中获取网站的域名?

如何从Django模板中获取当前站点的域名?我试着寻找标签和过滤器,但那里什么也没有。

How do I get the domain name of my current site from within a Django template? I’ve tried looking in the tag and filters but nothing there.


回答 0

我认为您想要的是可以访问请求上下文,请参见RequestContext。

I think what you want is to have access to the request context, see RequestContext.


回答 1

如果需要实际的HTTP Host标头,请参阅Daniel Roseman对@Phsiao答案的评论。另一种选择是,如果您使用的是contrib.sites框架,则可以在数据库中为站点设置一个规范域名(将请求域映射到具有正确SITE_ID的设置文件中,这是您必须通过自己的网络服务器设置)。在这种情况下,您要寻找:

from django.contrib.sites.models import Site

current_site = Site.objects.get_current()
current_site.domain

如果要使用current_site对象,则必须自己将其放在模板上下文中。如果您在各处使用它,则可以将其打包在模板上下文处理器中。

If you want the actual HTTP Host header, see Daniel Roseman’s comment on @Phsiao’s answer. The other alternative is if you’re using the contrib.sites framework, you can set a canonical domain name for a Site in the database (mapping the request domain to a settings file with the proper SITE_ID is something you have to do yourself via your webserver setup). In that case you’re looking for:

from django.contrib.sites.models import Site

current_site = Site.objects.get_current()
current_site.domain

you’d have to put the current_site object into a template context yourself if you want to use it. If you’re using it all over the place, you could package that up in a template context processor.


回答 2

我发现了{{ request.get_host }}方法。

I’ve discovered the {{ request.get_host }} method.


回答 3

作为对Carl Meyer的补充,您可以像这样创建一个上下文处理器:

module.context_processors.py

from django.conf import settings

def site(request):
    return {'SITE_URL': settings.SITE_URL}

本地settings.py

SITE_URL = 'http://google.com' # this will reduce the Sites framework db call.

settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    "module.context_processors.site",
    ....
 )

返回上下文实例的模板,URL站点为{{SITE_URL}}

如果要在上下文处理器中处理子域或SSL,则可以编写自己的例程。

Complementing Carl Meyer, you can make a context processor like this:

module.context_processors.py

from django.conf import settings

def site(request):
    return {'SITE_URL': settings.SITE_URL}

local settings.py

SITE_URL = 'http://google.com' # this will reduce the Sites framework db call.

settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    "module.context_processors.site",
    ....
 )

templates returning context instance the url site is {{ SITE_URL }}

you can write your own rutine if want to handle subdomains or SSL in the context processor.


回答 4

我使用的上下文处理器的变体是:

from django.contrib.sites.shortcuts import get_current_site
from django.utils.functional import SimpleLazyObject


def site(request):
    return {
        'site': SimpleLazyObject(lambda: get_current_site(request)),
    }

SimpleLazyObject包装可以确保DB调用只有当模板实际使用情况site的对象。这将从管理页面中删除查询。它还缓存结果。

并将其包含在设置中:

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    "module.context_processors.site",
    ....
)

在模板中,您可以{{ site.domain }}用来获取当前域名。

编辑:也要支持协议切换,请使用:

def site(request):
    site = SimpleLazyObject(lambda: get_current_site(request))
    protocol = 'https' if request.is_secure() else 'http'

    return {
        'site': site,
        'site_root': SimpleLazyObject(lambda: "{0}://{1}".format(protocol, site.domain)),
    }

The variation of the context processor I use is:

from django.contrib.sites.shortcuts import get_current_site
from django.utils.functional import SimpleLazyObject


def site(request):
    return {
        'site': SimpleLazyObject(lambda: get_current_site(request)),
    }

The SimpleLazyObject wrapper makes sure the DB call only happens when the template actually uses the site object. This removes the query from the admin pages. It also caches the result.

and include it in the settings:

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    "module.context_processors.site",
    ....
)

In the template, you can use {{ site.domain }} to get the current domain name.

edit: to support protocol switching too, use:

def site(request):
    site = SimpleLazyObject(lambda: get_current_site(request))
    protocol = 'https' if request.is_secure() else 'http'

    return {
        'site': site,
        'site_root': SimpleLazyObject(lambda: "{0}://{1}".format(protocol, site.domain)),
    }

回答 5

我知道这个问题很老,但是我偶然发现了这个问题,寻找一种获取当前域的pythonic方法。

def myview(request):
    domain = request.build_absolute_uri('/')[:-1]
    # that will build the complete domain: http://foobar.com

I know this question is old, but I stumbled upon it looking for a pythonic way to get current domain.

def myview(request):
    domain = request.build_absolute_uri('/')[:-1]
    # that will build the complete domain: http://foobar.com

回答 6

快速简单,但不适用于生产:

(在视图中)

    request.scheme               # http or https
    request.META['HTTP_HOST']    # example.com
    request.path                 # /some/content/1/

(在模板中)

{{ request.scheme }} :// {{ request.META.HTTP_HOST }} {{ request.path }}

确保使用RequestContext,如果使用render,就是这种情况。

不要相信request.META['HTTP_HOST']生产:该信息来自浏览器。而是使用@CarlMeyer的答案

Quick and simple, but not good for production:

(in a view)

    request.scheme               # http or https
    request.META['HTTP_HOST']    # example.com
    request.path                 # /some/content/1/

(in a template)

{{ request.scheme }} :// {{ request.META.HTTP_HOST }} {{ request.path }}

Be sure to use a RequestContext, which is the case if you’re using render.

Don’t trust request.META['HTTP_HOST'] in production: that info comes from the browser. Instead, use @CarlMeyer’s answer


回答 7

{{ request.get_host }}ALLOWED_HOSTS设置(在Django 1.4.4中添加)一起使用时,应该可以防止HTTP Host标头攻击。

请注意,{{ request.META.HTTP_HOST }}没有相同的保护。见文档

ALLOWED_HOSTS

代表此Django站点可以服务的主机/域名的字符串列表。这是一种安全措施,可以防止HTTP Host标头攻击,即使在许多看似安全的Web服务器配置下也可能发生这种攻击

…如果Host标头(或者X-Forwarded-Host如果USE_X_FORWARDED_HOST使能)不匹配,在此列表中的任何值,该django.http.HttpRequest.get_host()方法将提高SuspiciousOperation

…此验证仅通过进行get_host();如果您的代码直接从request.META您访问Host标头,则绕过此安全保护措施。


至于request在模板中使用,在Django 1.8中,模板渲染函数调用已更改,因此您不再需要RequestContext直接处理。

这是使用快捷功能为视图渲染模板的方法render()

from django.shortcuts import render

def my_view(request):
    ...
    return render(request, 'my_template.html', context)

这是呈现电子邮件模板的方法,在您需要主机值的情况下,IMO是最常见的情况:

from django.template.loader import render_to_string

def my_view(request):
    ...
    email_body = render_to_string(
        'my_template.txt', context, request=request)

这是在电子邮件模板中添加完整URL的示例;request.scheme应该获得httphttps取决于您使用的是什么:

Thanks for registering! Here's your activation link:
{{ request.scheme }}://{{ request.get_host }}{% url 'registration_activate' activation_key %}

{{ request.get_host }} should protect against HTTP Host header attacks when used together with the ALLOWED_HOSTS setting (added in Django 1.4.4).

Note that {{ request.META.HTTP_HOST }} does not have the same protection. See the docs:

ALLOWED_HOSTS

A list of strings representing the host/domain names that this Django site can serve. This is a security measure to prevent HTTP Host header attacks, which are possible even under many seemingly-safe web server configurations.

… If the Host header (or X-Forwarded-Host if USE_X_FORWARDED_HOST is enabled) does not match any value in this list, the django.http.HttpRequest.get_host() method will raise SuspiciousOperation.

… This validation only applies via get_host(); if your code accesses the Host header directly from request.META you are bypassing this security protection.


As for using the request in your template, the template-rendering function calls have changed in Django 1.8, so you no longer have to handle RequestContext directly.

Here’s how to render a template for a view, using the shortcut function render():

from django.shortcuts import render

def my_view(request):
    ...
    return render(request, 'my_template.html', context)

Here’s how to render a template for an email, which IMO is the more common case where you’d want the host value:

from django.template.loader import render_to_string

def my_view(request):
    ...
    email_body = render_to_string(
        'my_template.txt', context, request=request)

Here’s an example of adding a full URL in an email template; request.scheme should get http or https depending on what you’re using:

Thanks for registering! Here's your activation link:
{{ request.scheme }}://{{ request.get_host }}{% url 'registration_activate' activation_key %}

回答 8

我使用自定义模板标签。添加到例如<your_app>/templatetags/site.py

# -*- coding: utf-8 -*-
from django import template
from django.contrib.sites.models import Site

register = template.Library()

@register.simple_tag
def current_domain():
    return 'http://%s' % Site.objects.get_current().domain

在这样的模板中使用它:

{% load site %}
{% current_domain %}

I use a custom template tag. Add to e.g. <your_app>/templatetags/site.py:

# -*- coding: utf-8 -*-
from django import template
from django.contrib.sites.models import Site

register = template.Library()

@register.simple_tag
def current_domain():
    return 'http://%s' % Site.objects.get_current().domain

Use it in a template like this:

{% load site %}
{% current_domain %}

回答 9

与用户panchicore的回复类似,这是我在一个非常简单的网站上所做的。它提供了一些变量并使它们在模板上可用。

SITE_URL将举行一个类似的值example.com
SITE_PROTOCOL将举行类似的值httphttps
SITE_PROTOCOL_URL将举行类似的值http://example.comhttps://example.com
SITE_PROTOCOL_RELATIVE_URL将持有的值等//example.com

module / context_processors.py

from django.conf import settings

def site(request):

    SITE_PROTOCOL_RELATIVE_URL = '//' + settings.SITE_URL

    SITE_PROTOCOL = 'http'
    if request.is_secure():
        SITE_PROTOCOL = 'https'

    SITE_PROTOCOL_URL = SITE_PROTOCOL + '://' + settings.SITE_URL

    return {
        'SITE_URL': settings.SITE_URL,
        'SITE_PROTOCOL': SITE_PROTOCOL,
        'SITE_PROTOCOL_URL': SITE_PROTOCOL_URL,
        'SITE_PROTOCOL_RELATIVE_URL': SITE_PROTOCOL_RELATIVE_URL
    }

settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    "module.context_processors.site",
    ....
 )

SITE_URL = 'example.com'

然后,在你的模板,把它们作为{{ SITE_URL }}{{ SITE_PROTOCOL }}{{ SITE_PROTOCOL_URL }}{{ SITE_PROTOCOL_RELATIVE_URL }}

Similar to user panchicore’s reply, this is what I did on a very simple website. It provides a few variables and makes them available on the template.

SITE_URL would hold a value like example.com
SITE_PROTOCOL would hold a value like http or https
SITE_PROTOCOL_URL would hold a value like http://example.com or https://example.com
SITE_PROTOCOL_RELATIVE_URL would hold a value like //example.com.

module/context_processors.py

from django.conf import settings

def site(request):

    SITE_PROTOCOL_RELATIVE_URL = '//' + settings.SITE_URL

    SITE_PROTOCOL = 'http'
    if request.is_secure():
        SITE_PROTOCOL = 'https'

    SITE_PROTOCOL_URL = SITE_PROTOCOL + '://' + settings.SITE_URL

    return {
        'SITE_URL': settings.SITE_URL,
        'SITE_PROTOCOL': SITE_PROTOCOL,
        'SITE_PROTOCOL_URL': SITE_PROTOCOL_URL,
        'SITE_PROTOCOL_RELATIVE_URL': SITE_PROTOCOL_RELATIVE_URL
    }

settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    "module.context_processors.site",
    ....
 )

SITE_URL = 'example.com'

Then, on your templates, use them as {{ SITE_URL }}, {{ SITE_PROTOCOL }}, {{ SITE_PROTOCOL_URL }} and {{ SITE_PROTOCOL_RELATIVE_URL }}


回答 10

在Django模板中,您可以执行以下操作:

<a href="{{ request.scheme }}://{{ request.META.HTTP_HOST }}{{ request.path }}?{{ request.GET.urlencode }}" >link</a>

In a Django template you can do:

<a href="{{ request.scheme }}://{{ request.META.HTTP_HOST }}{{ request.path }}?{{ request.GET.urlencode }}" >link</a>

回答 11

如果您使用“请求”上下文处理器,并且正在使用Django sites框架,并且安装了Site中间件(即您的设置包括以下内容):

INSTALLED_APPS = [
    ...
    "django.contrib.sites",
    ...
]

MIDDLEWARE = [
    ...
     "django.contrib.sites.middleware.CurrentSiteMiddleware",
    ...
]

TEMPLATES = [
    {
        ...
        "OPTIONS": {
            "context_processors": [
                ...
                "django.template.context_processors.request",
                ...
            ]
        }
    }
]

…然后您将request在模板中使用该对象,并且该对象将包含对当前Site请求的引用request.site。然后,您可以使用以下模板在模板中检索域:

    {{request.site.domain}}

If you use the “request” context processor, and are using the Django sites framework, and have the Site middleware installed (i.e. your settings include these):

INSTALLED_APPS = [
    ...
    "django.contrib.sites",
    ...
]

MIDDLEWARE = [
    ...
     "django.contrib.sites.middleware.CurrentSiteMiddleware",
    ...
]

… then you will have the request object available in templates, and it will contain a reference to the current Site for the request as request.site. You can then retrieve the domain in a template with:

    {{request.site.domain}}

and the site name with:

    {{request.site.name}}

回答 12

那这种方法呢?为我工作。它也用于django-registration中

def get_request_root_url(self):
    scheme = 'https' if self.request.is_secure() else 'http'
    site = get_current_site(self.request)
    return '%s://%s' % (scheme, site)

What about this approach? Works for me. It is also used in django-registration.

def get_request_root_url(self):
    scheme = 'https' if self.request.is_secure() else 'http'
    site = get_current_site(self.request)
    return '%s://%s' % (scheme, site)

回答 13

from django.contrib.sites.models import Site
if Site._meta.installed:
    site = Site.objects.get_current()
else:
    site = RequestSite(request)
from django.contrib.sites.models import Site
if Site._meta.installed:
    site = Site.objects.get_current()
else:
    site = RequestSite(request)

回答 14

您可以{{ protocol }}://{{ domain }}在模板中使用来获取域名。

You can use {{ protocol }}://{{ domain }} in your templates to get your domain name.


Django模板变量和Javascript

问题:Django模板变量和Javascript

当我使用Django模板渲染器渲染页面时,可以传入包含各种值的字典变量,以使用来在页面中对其进行操作{{ myVar }}

有没有办法在Javascript中访问相同的变量(也许使用DOM,我不知道Django如何使变量可访问)?我希望能够基于传入的变量中包含的值使用AJAX查找来查找详细信息。

When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using {{ myVar }}.

Is there a way to access the same variable in Javascript (perhaps using the DOM, I don’t know how Django makes the variables accessible)? I want to be able to lookup details using an AJAX lookup based on the values contained in the variables passed in.


回答 0

{{variable}}直接替换为HTML。查看资料;它不是“变量”或类似的变量。它只是渲染的文本。

话虽如此,您可以将这种替换形式添加到JavaScript中。

<script type="text/javascript"> 
   var a = "{{someDjangoVariable}}";
</script>

这为您提供了“动态” javascript。

The {{variable}} is substituted directly into the HTML. Do a view source; it isn’t a “variable” or anything like it. It’s just rendered text.

Having said that, you can put this kind of substitution into your JavaScript.

<script type="text/javascript"> 
   var a = "{{someDjangoVariable}}";
</script>

This gives you “dynamic” javascript.


回答 1

注意检查票证#17419,以获取有关将类似的标签添加到Django核心中的讨论以及通过将此模板标签与用户生成的数据一起使用而引入的可能的XSS漏洞。amacneil的评论讨论了故障单中提出的大多数问题。


我认为最灵活,方便的方法是为要在JS代码中使用的变量定义模板过滤器。这样可以确保您的数据已正确转义,并且可以将其用于复杂的数据结构,例如dictlist。这就是为什么我写这个答案的原因,尽管有一个被广泛接受的答案。

这是模板过滤器的示例:

// myapp/templatetags/js.py

from django.utils.safestring import mark_safe
from django.template import Library

import json


register = Library()


@register.filter(is_safe=True)
def js(obj):
    return mark_safe(json.dumps(obj))

此模板过滤器将变量转换为JSON字符串。您可以这样使用它:

// myapp/templates/example.html

{% load js %}

<script type="text/javascript">
    var someVar = {{ some_var | js }};
</script>

CAUTION Check ticket #17419 for discussion on adding similar tag into Django core and possible XSS vulnerabilities introduced by using this template tag with user generated data. Comment from amacneil discusses most of the concerns raised in the ticket.


I think the most flexible and handy way of doing this is to define a template filter for variables you want to use in JS code. This allows you to ensure, that your data is properly escaped and you can use it with complex data structures, such as dict and list. That’s why I write this answer despite there is an accepted answer with a lot of upvotes.

Here is an example of template filter:

// myapp/templatetags/js.py

from django.utils.safestring import mark_safe
from django.template import Library

import json


register = Library()


@register.filter(is_safe=True)
def js(obj):
    return mark_safe(json.dumps(obj))

This template filters converts variable to JSON string. You can use it like so:

// myapp/templates/example.html

{% load js %}

<script type="text/javascript">
    var someVar = {{ some_var | js }};
</script>

回答 2

对我有用的解决方案是使用模板中的隐藏输入字段

<input type="hidden" id="myVar" name="variable" value="{{ variable }}">

然后以这种方式在javascript中获取值,

var myVar = document.getElementById("myVar").value;

A solution that worked for me is using the hidden input field in the template

<input type="hidden" id="myVar" name="variable" value="{{ variable }}">

Then getting the value in javascript this way,

var myVar = document.getElementById("myVar").value;

回答 3

从Django 2.1开始,专门针对此用例引入了一个新的内置模板标记:json_script

https://docs.djangoproject.com/zh-CN/3.0/ref/templates/builtins/#json-script

新标签将安全地序列化模板值并防止XSS。

Django文档摘录:

安全地将Python对象作为JSON输出,包装在标记中,可以与JavaScript一起使用。

As of Django 2.1, a new built in template tag has been introduced specifically for this use case: json_script.

https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#json-script

The new tag will safely serialize template values and protects against XSS.

Django docs excerpt:

Safely outputs a Python object as JSON, wrapped in a tag, ready for use with JavaScript.


回答 4

这是我很容易做的事情:我为模板修改了base.html文件,并将其放在底部:

{% if DJdata %}
    <script type="text/javascript">
        (function () {window.DJdata = {{DJdata|safe}};})();
    </script>
{% endif %}

然后,当我想在javascript文件中使用变量时,我创建了一个DJdata字典,并通过json将其添加到上下文中: context['DJdata'] = json.dumps(DJdata)

希望能帮助到你!

Here is what I’m doing very easily: I modified my base.html file for my template and put that at the bottom:

{% if DJdata %}
    <script type="text/javascript">
        (function () {window.DJdata = {{DJdata|safe}};})();
    </script>
{% endif %}

then when I want to use a variable in the javascript files, I create a DJdata dictionary and I add it to the context by a json : context['DJdata'] = json.dumps(DJdata)

Hope it helps!


回答 5

对于字典,最好先编码为JSON。您可以使用simplejson.dumps(),或者如果要从App Engine中的数据模型进行转换,则可以使用GQLEncoder库中的encode()。

For a dictionary, you’re best of encoding to JSON first. You can use simplejson.dumps() or if you want to convert from a data model in App Engine, you could use encode() from the GQLEncoder library.


回答 6

我面临着类似的问题,S.Lott建议的答案为我工作。

<script type="text/javascript"> 
   var a = "{{someDjangoVariable}}"
</script>

但是,我想在这里指出主要的实现限制。如果您打算将javascript代码放在其他文件中,然后将该文件包含在模板中。这行不通。

仅当主模板和javascript代码位于同一文件中时,此方法才有效。也许django小组可以解决这个限制。

I was facing simillar issue and answer suggested by S.Lott worked for me.

<script type="text/javascript"> 
   var a = "{{someDjangoVariable}}"
</script>

However I would like to point out major implementation limitation here. If you are planning to put your javascript code in different file and include that file in your template. This won’t work.

This works only when you main template and javascript code is in same file. Probably django team can address this limitation.


回答 7

我也一直在为此苦苦挣扎。从表面上看,上述解决方案应该可行。但是,django架构要求每个html文件都有其自己的呈现变量(即{{contact}}呈现为contact.html,而呈现{{posts}}给eg index.html等)。另一方面,<script>标记出现{%endblock%}base.htmlfrom的后面contact.htmlindex.html继承。这基本上意味着任何解决方案,包括

<script type="text/javascript">
    var myVar = "{{ myVar }}"
</script>

必然会失败,因为变量和脚本不能共存于同一文件中。

我最终想出并为我工作的一个简单解决方案是,简单地用带有id的标签包装变量,然后在js文件中引用它,如下所示:

// index.html
<div id="myvar">{{ myVar }}</div>

然后:

// somecode.js
var someVar = document.getElementById("myvar").innerHTML;

并且只包含<script src="static/js/somecode.js"></script>base.html照常进行。当然,这只是关于获取内容。关于安全性,只需遵循其他答案即可。

I’ve been struggling with this too. On the surface it seems that the above solutions should work. However, the django architecture requires that each html file has its own rendered variables (that is, {{contact}} is rendered to contact.html, while {{posts}} goes to e.g. index.html and so on). On the other hand, <script> tags appear after the {%endblock%} in base.html from which contact.html and index.html inherit. This basically means that any solution including

<script type="text/javascript">
    var myVar = "{{ myVar }}"
</script>

is bound to fail, because the variable and the script cannot co-exist in the same file.

The simple solution I eventually came up with, and worked for me, was to simply wrap the variable with a tag with id and later refer to it in the js file, like so:

// index.html
<div id="myvar">{{ myVar }}</div>

and then:

// somecode.js
var someVar = document.getElementById("myvar").innerHTML;

and just include <script src="static/js/somecode.js"></script> in base.html as usual. Of course this is only about getting the content. Regarding security, just follow the other answers.


回答 8

对于以文本形式存储在Django字段中的JavaScript对象,它需要再次成为动态插入页面脚本中的JavaScript对象,您需要同时使用escapejsJSON.parse()

var CropOpts = JSON.parse("{{ profile.last_crop_coords|escapejs }}");

Django的escapejs句柄正确处理了引号,JSON.parse()并将字符串转换回JS对象。

For a JavaScript object stored in a Django field as text, which needs to again become a JavaScript object dynamically inserted into on-page script, you need to use both escapejs and JSON.parse():

var CropOpts = JSON.parse("{{ profile.last_crop_coords|escapejs }}");

Django’s escapejs handles the quoting properly, and JSON.parse() converts the string back into a JS object.


回答 9

请注意,如果要将变量传递给外部.js脚本,则需要在脚本标签之前加上另一个声明全局变量的脚本标签。

<script type="text/javascript">
    var myVar = "{{ myVar }}"
</script>

<script type="text/javascript" src="{% static "scripts/my_script.js" %}"></script>

data 在视图中照常定义 get_context_data

def get_context_data(self, *args, **kwargs):
    context['myVar'] = True
    return context

Note, that if you want to pass a variable to an external .js script then you need to precede your script tag with another script tag that declares a global variable.

<script type="text/javascript">
    var myVar = "{{ myVar }}"
</script>

<script type="text/javascript" src="{% static "scripts/my_script.js" %}"></script>

data is defined in the view as usual in the get_context_data

def get_context_data(self, *args, **kwargs):
    context['myVar'] = True
    return context

回答 10

我在Django 2.1中使用这种方式并为我工作,这种方式很安全(参考)

Django方面:

def age(request):
    mydata = {'age':12}
    return render(request, 'test.html', context={"mydata_json": json.dumps(mydata)})

HTML方面:

<script type='text/javascript'>
     const  mydata = {{ mydata_json|safe }};
console.log(mydata)
 </script>

I use this way in Django 2.1 and work for me and this way is secure (reference):

Django side:

def age(request):
    mydata = {'age':12}
    return render(request, 'test.html', context={"mydata_json": json.dumps(mydata)})

Html side:

<script type='text/javascript'>
     const  mydata = {{ mydata_json|safe }};
console.log(mydata)
 </script>

回答 11

您可以在字符串中声明数组变量的地方组装整个脚本,如下所示,

views.py

    aaa = [41, 56, 25, 48, 72, 34, 12]
    prueba = "<script>var data2 =["
    for a in aaa:
        aa = str(a)
        prueba = prueba + "'" + aa + "',"
    prueba = prueba + "];</script>"

将生成如下字符串

prueba = "<script>var data2 =['41','56','25','48','72','34','12'];</script>"

拥有此字符串后,必须将其发送到模板

views.py

return render(request, 'example.html', {"prueba": prueba})

在模板中,您会收到它,并以书面形式将其解释为htm代码,例如您需要的javascript代码之前

模板

{{ prueba|safe  }}

在代码的其余部分下面,请记住,在示例中使用的变量是data2

<script>
 console.log(data2);
</script>

这样,您将保留数据类型,在这种情况下,这是一种安排

you can assemble the entire script where your array variable is declared in a string, as follows,

views.py

    aaa = [41, 56, 25, 48, 72, 34, 12]
    prueba = "<script>var data2 =["
    for a in aaa:
        aa = str(a)
        prueba = prueba + "'" + aa + "',"
    prueba = prueba + "];</script>"

that will generate a string as follows

prueba = "<script>var data2 =['41','56','25','48','72','34','12'];</script>"

after having this string, you must send it to the template

views.py

return render(request, 'example.html', {"prueba": prueba})

in the template you receive it and interpret it in a literary way as htm code, just before the javascript code where you need it, for example

template

{{ prueba|safe  }}

and below that is the rest of your code, keep in mind that the variable to use in the example is data2

<script>
 console.log(data2);
</script>

that way you will keep the type of data, which in this case is an arrangement


回答 12

Javascript中有两件事对我有用:

'{{context_variable|escapejs }}'

其他:在views.py中

from json import dumps as jdumps

def func(request):
    context={'message': jdumps('hello there')}
    return render(request,'index.html',context)

并在html中:

{{ message|safe }}

There are two things that worked for me inside Javascript:

'{{context_variable|escapejs }}'

and other: In views.py

from json import dumps as jdumps

def func(request):
    context={'message': jdumps('hello there')}
    return render(request,'index.html',context)

and in the html:

{{ message|safe }}