如何在Django中将变量从视图传递到基.html?

我想在项目的导航栏上显示用户的名字。此导航栏位于文件上。base.html


在我的应用程序中,我创建了一个执行此操作的变量views.py


def base(request):

    user = request.user

    u = User.objects.get(username=user)

    us = u.clients.first_name

    context = {'u': u, 'us': us}

    return render(request, "backend/base.html", context)

我可以让它在任何其他.html文件上工作,但不能在基础.html上工作,看起来像这样


<span class="mb-0 text-sm  font-weight-bold">{{us}}</span>

这是我的模型


class Clients(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)

    first_name = models.CharField(max_length=30, verbose_name="Primeiro Nome")

    last_name = models.CharField(max_length=30, verbose_name="Apelido")

    address = models.CharField(max_length=200, verbose_name="Morada")

    nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], primary_key=True)

    mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')])

    email = models.CharField(max_length=200, null=True, verbose_name="Email")


    def __str__(self):

        return "%s %s" % (self.first_name, self.last_name)


    class Meta:

        verbose_name_plural = "Clientes"


尚方宝剑之说
浏览 89回答 2
2回答

Helenr

我正在回答我自己的问题。我能够通过使用以下代码创建一个来解决此问题context_processor.pyfrom .models import Clients, Hotels, Trip, Flightfrom django.contrib.auth.models import Userdef add_variable_to_context(request):&nbsp;&nbsp;&nbsp; &nbsp; user = request.user&nbsp; &nbsp; u = User.objects.get(username=user)&nbsp; &nbsp; us = u.clients.first_name&nbsp; &nbsp; uv = u.clients.avatar&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; 'u': u,&nbsp; &nbsp; &nbsp; &nbsp; 'us': us,&nbsp; &nbsp; &nbsp; &nbsp; 'uv': uv&nbsp; &nbsp; }

ibeautiful

在 views.py 尝试使用render_to_string函数。不要忘记在配置文件中配置静态文件设置。from django.template.loader import render_to_stringcontext = {'u': u, 'us': us}render_to_string('html_name.html', context)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python