简体   繁体   English

如何在 django 模板中使用 django model object 模板?

[英]how to use django model object in django templates?

I am not able to use the Django model object in Django templates.我无法在 ZEF0F93C83E374876A61DA0D4D16F3 模板中使用 Django model object。 I want to iterate using the model user in the template and then play with the ActivityPeriod(model) of that user.我想在模板中使用 model 用户进行迭代,然后使用该用户的 ActivityPeriod(model)。 Please check my code for the clarity:请检查我的代码是否清晰:

Here is my code:这是我的代码:

views.py视图.py

from .models import User,ActivityPeriod

def call_response(request):
    user = User.objects.all()
    return render(request, "Test/list.html", {"users":user ,"activityperiod":ActivityPeriod})

Test/list.html测试/列出.html

{% for user in users %}
    'real_name': {{ user.real_name}}},
    'activity_periods': {% with activity=activityperiod.objects.get(id =user) %}
    {{ activity.start_time }}
    {% endwith %}
{% endfor %}

But i am getting an error: Could not parse the remainder: '(id' from 'activityperiod.objects.get(id'但我收到一个错误:无法解析剩余部分:'(id' from 'activityperiod.objects.get(id'

What is the correct way?正确的方法是什么? Can anyone please share it with me.任何人都可以与我分享。

Django template don't understand the filter action of Model. Django 模板不理解 Model 的过滤动作。 This part shoud be in view.这部分应该放在眼里。

activity=activityperiod.objects.get(id =user)

You should prepare your data and manipulate them before sending to template (a dictionary may help you).您应该在发送到模板之前准备好数据并对其进行操作(字典可能会对您有所帮助)。 And remember that result of action "User.objects.all()" is a list.请记住,操作“User.objects.all()”的结果是一个列表。

Your question suggests that you think you can a function in the templates like a normal function (ie activityperiod.objects.get(...) ).您的问题表明您认为您可以在模板中使用 function ,就像普通的 function (即activityperiod.objects.get(...) )。

You can't, the templating system is not made like this (for security reasons amongst others).你不能,模板系统不是这样制作的(出于安全原因等)。

You should do something like, in your models:您应该在模型中执行以下操作:

def call_response(request):
    # ! first() not "all()" (if > 1 user, you'll have problem)!
    user = User.objects.first()
    activityperiod = activityperiod.objects.get(user=user)
    return render(request, "Test/list.html",
                  {"users":user ,"activityperiod":activityperiod})

views.py视图.py

def call_response(request):

user = User.objects.filter(user=request.user)
activityperiod = activityperiod.objects.get(user=user)
context={'user':user,'activityperiod':activityperiod}
return render(request, "Test/list.html",context})

Test/list.html测试/列出.html

'real_name': {{ user.real_name}}
'activity_periods':{{ activityperiod.start_time }}

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

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