Django在模板中打印变量

2024-06-25 23:26:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个名为“作业”的应用程序,基本上我想从管理控制台创建新的“作业”,并能够将其发布在jobs.html页面上

我创建了模型和视图,但我认为视图有问题,不允许我在html模板上打印“作业”

您能告诉我错误是否在views.py中吗

jobs/models.py

from django.db import models

# Create your models here.
class post_job(models.Model):
    posizione= models.TextField(max_length=20)
    descrizione= models.TextField(max_length=20)
    requisiti= models.TextField(max_length=20)

    def __str__(self):
        """String for representing the MyModelName object (in Admin site etc.)."""
        return self.posizione

jobs/admin.py

from django.contrib import admin
from .models import post_job
# Register your models here.

admin.site.register(post_job)

jobs/views.py

from django.shortcuts import render
from .models import post_job
# Create your views here.

def viz_job(request):
    posizione = post_job.posizione
    print(posizione)
    return render(request,'jobs/jobs.html',{'posizione':posizione})

Tags: djangofrompyimportyourheremodelshtml
2条回答

您必须知道要为模板返回什么,例如在views.py中:

from django.shortcuts import render
from .models import post_job
# Create your views here.

def viz_job(request):
    jobs = []
    descriziones = []
    posizione = Job.objects.all()
    for pos in posizione:
        jobs.append(pos.posizione)
        descriziones.append(pos.descrizione)
    context = {
        'posizione': jobs,
        'descrizione': descriziones
    }
    return render(request, 'jobs/jobs.html',
                  context=context)  # this will return context dictonary to the template

您可以进行筛选并从数据库中获取特定数据

正确答案:

在你看来:

from django.shortcuts import render
from .models import PostJob # proper naming

def viz_job(request):
    jobs = PostJob.objects.all()

    return render(request,'jobs/jobs.html',{'jobs': jobs})

在模板中:

<ul>
{% for job in jobs %}
   <li>
      <h3>{{ job.posizione }}</h3>
      <div>
          {{ job.descrizione }}
     </div>
   </li>
{% endfor %}
</ul>

请注意,所有这些都已记录在案

注意:如果您只对这两个字段感兴趣,并且不需要模型的任何方法、相关对象或任何东西,那么可以通过使用values查询集稍微优化查询,该查询集将生成包含所选字段的dict,而不是完整的模型实例:

    jobs = PostJob.objects.values("posizione", "descrizione")

其他一切都是一样的

相关问题 更多 >