简体   繁体   English

如何更改django模板中的现有变量

[英]How to change an existing variable in a django template

Newish to Django here and need some assistance. 在这里向Django求爱并需要一些帮助。 I have a bool variable empty=True. 我有一个bool变量empty = True。 I passed the variable through views to my template successfully. 我通过视图将变量成功传递给了我的模板。 In the template I have a while loop that includes an if/else statement. 在模板中,我有一个包含if / else语句的while循环。 I need to be able to change my variable to False if it meets a condition in the if statement. 如果它满足if语句中的条件,我需要能够将我的变量更改为False。 Once I'm out of the loop there is another if/else statement to check in empty is True. 一旦我退出循环,就会有另一个if / else语句检查为空是True。

I can't seem to figure out how to change a variable in the template. 我似乎无法弄清楚如何更改模板中的变量。

I did try a with statement to change the variable but it didn't work correctly for me because I have to end the with statement before the loop ends. 我确实尝试使用with语句来更改变量,但它对我来说无法正常工作,因为我必须在循环结束前结束with语句。 Once the with statement ends, the variable reverts back to its' original value 一旦with语句结束,变量将恢复为其原始值

Views - ''' 意见 - '''

def myProjects(request):
    user = request.user
    projects = Project.objects.all() #from db
    empty=True
    return render(request,'users/myProjects.html',locals())

''' Template - ''' '''模板 - '''

<div class="row" id="main1">
  <div class="col-2"></div>
  <div class="col-9">
    <div>
      <h1>My Projects: </h1>
      {% for x in proj %}
        {% if x.creator.user == me %}
          <div class="media1">
            <img class="account-img" src="{{x.projectPicture.url}}">
            <div>
              <h5><strong>Project Name: {{x.projectName}}</strong></h5>
              <p>Project Type: {{x.projectType}}</p>
              <p>Creator: <a href="/allUsers?name1={{x.creator.user}}"> {{x.creator.user}} </a></p>
              <p class="text-muted small">Created: {{x.dateTime}}</p>
            </div>
          </div>
          {{empty=False}}
        {% else %}
          {{pass}}
        {% endif %}

      {% if empty==True %}
        <p>You do not have any projects</p>
      {% else %}
        {{pass}}
      {% endif %}
      {% endfor %}
    </div>
  </div>
</div>

{% endblock%}

''' “””

Setting variable values in templates is against Django's design philosophy. 在模板中设置变量值是违反Django的设计理念的。 The template system is designed to separate logic from presentation and avoid being a programming language . 模板系统旨在将逻辑与表示分开避免成为编程语言

To achieve what you are trying to do, you could first filter the projects in the view, then use the for...empty tag. 要实现您要执行的操作,您可以先在视图中过滤项目,然后使用for ... empty标记。 Your example would become something like the following: 您的示例将变为如下所示:

{% for project in projects_created_by_me %}
  <p>Project Name: {{project.projectName}}</p>
{% empty %}
  <p>You do not have any projects</p>
{% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM