我如何在 Django 中用选择的字符串替换没有用户名 [英] how do I replace no username with a string of choice in Django

查看:23
本文介绍了我如何在 Django 中用选择的字符串替换没有用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当工单没有用户时,我希望未分配用户".

I would like to have 'No user assigned' when there is no user to the ticket.

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

I did this to my model but I don't see any changes

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

其中分配的是分配给票证的用户.

where assigned is the user assigned for a ticket.

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

IS ther any other way to do this?

我有我的模板和视图:

{% 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

推荐答案

您可以使用 for...empty

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

It doesn't make much sense to include it in a model so you can just provide a default if the thing being iterated over in the for loop is empty

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

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

The advantage here is you could always use the empty section to insert a button into your table to allow people to be assigned (for example).

这篇关于我如何在 Django 中用选择的字符串替换没有用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆