how do I replace no username with a string of choice in Django

橙三吉。 提交于 2019-12-02 18:29:30

问题


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?

I have my template and view like 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>

and my View:

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

回答1:


You can use for...empty

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

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).




回答2:


Try use {{ user }} instead {{ user.email }}



来源:https://stackoverflow.com/questions/36576035/how-do-i-replace-no-username-with-a-string-of-choice-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!