【问题标题】:how do I replace no username with a string of choice in Django如何在Django中用选择的字符串替换没有用户名
【发布时间】:2016-08-03 05:29:46
【问题描述】:

当工单没有用户时,我希望“未分配用户”。

我对我的模型做了这个,但我没有看到任何变化

def __unicode__(self):
        print 'gets here****'
        if not self.assigned:
            return 'No user assigned'
        else:
            return self.assigned

其中assigned 是分配给工单的用户。

还有其他方法可以做到这一点吗?

我有这样的模板和视图:

{% for ticket in tickets %}
                <tr>
                    <td>{{ ticket.title }}</td>
                    <td>
                    {% for user in ticket.assigned.all %}
                        {{ user.email }}{% if not forloop.last %},{% endif %}
                    {% endfor %}
                    </td>

和我的观点:

def get_data(self, **kwargs):
        context = super(View, self).get_data(**kwargs)
        project = self.project_described()

        context.update({
            "project": project,
            "tickets": project.tickets.all()
        })
        return context

【问题讨论】:

    标签: django django-models django-templates


    【解决方案1】:

    您可以使用for...empty

    将它包含在模型中没有多大意义,因此如果在 for 循环中迭代的内容为空,您只需提供默认值

    {% for user in ticket.assigned.all %}
         {{ user.email }}{% if not forloop.last %},{% endif %}
    {% empty %}
      No user assigned 
    {% endfor %}
    

    这里的优点是您始终可以使用empty 部分在您的表格中插入一个按钮以允许分配人员(例如)。

    【讨论】:

      【解决方案2】:

      尝试使用{{ user }} 代替{{ user.email }}

      【讨论】:

      • 对于正在审查的人来说,从技术上讲,这个答案可能实际上解决了问题,因为它会调用正确的方法
      猜你喜欢
      • 2017-10-22
      • 2021-09-26
      • 1970-01-01
      • 2013-01-30
      • 2014-08-31
      • 2016-03-26
      • 2020-08-28
      • 2013-08-17
      • 2012-08-01
      相关资源
      最近更新 更多