如何显示Django对象模型的一部分?

问题描述 投票:0回答:3

我试图在Django中显示数据库的字段,当用户不是超级用户时,给定一个像GR96 0810 0010 0000 0123 4567 890的字段,该值在任何地方都应显示为---7890,这是我的代码:

view.py: 

def index(request):
    obj = MyModel.objects.all()
    if request.user.is_superuser:
        return render(request, 'app/index.html', {'obj': obj})
    else:
        obj = len(str(obj))-5
        return render(request, 'app/index.html', {'obj': obj})

Template:
{% for ele in obj %}
    <tr>
      <th scope="row">{{ ele.id }}</th>
      <td>{{ ele }}</td>
    </tr>
{%  endfor %}


This is error:
TypeError at /
'int' object is not iterable

Request Method:     GET
Request URL:    http://127.0.0.1:8000/
Django Version:     3.0
Exception Type:     TypeError
Exception Value:    

'int' object is not iterable
....

您能帮我吗?预先谢谢你

python django web typeerror iterable
3个回答
0
投票

在else语句中,您将obj重新声明为整数值,因此无法在模板中对其进行迭代。我建议在用户为超级管理员时编辑返回值:

view.py:

def index(request):
    obj = MyModel.objects.all()
    if request.user.is_superuser:
        return render(request, 'app/index.html', {'obj': obj})
    else:
        for single_obj in obj:
           single_obj.your_field_name = "--" + single_obj.your_field_name.replace(" ", "")[-4:]
        return render(request, 'app/index.html', {'obj': obj})

0
投票

obj是类型为[[MyModel的对象的列表。

在您的[[else条件下:

obj = len(str(obj))-5 您将obj更改为整数。您应该改为这样做:

for idx, o in enumerate(obj):
     obj[idx].id = o[len(str(o.id)) - 5:]
这将从

obj中的每个MyModel对象提取最后5个字符。


0
投票
© www.soinside.com 2019 - 2024. All rights reserved.