Django - 在模板中打印变量

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


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


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


工作/模型.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

工作/admin.py


from django.contrib import admin

from .models import post_job

# Register your models here.


admin.site.register(post_job)

工作/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})


哔哔one
浏览 243回答 2
2回答

慕娘9325324

正确答案:在您看来:from django.shortcuts import renderfrom .models import PostJob # proper namingdef viz_job(request):&nbsp; &nbsp; jobs = PostJob.objects.all()&nbsp; &nbsp; return render(request,'jobs/jobs.html',{'jobs': jobs})在您的模板中:<ul>{% for job in jobs %}&nbsp; &nbsp;<li>&nbsp; &nbsp; &nbsp; <h3>{{ job.posizione }}</h3>&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {{ job.descrizione }}&nbsp; &nbsp; &nbsp;</div>&nbsp; &nbsp;</li>{% endfor %}</ul>请注意,所有这些都已记录在案。注意:如果您只对这两个字段感兴趣并且不需要任何模型的方法、相关对象或其他任何东西,您可以通过使用查询集来优化查询,该查询values集将产生带有所选字段而不是完整的字典模型实例:&nbsp; &nbsp; jobs = PostJob.objects.values("posizione", "descrizione")其他一切都保持不变。

白衣染霜花

您必须知道要为模板返回什么,例如在 views.py 中:from django.shortcuts import renderfrom .models import post_job# Create your views here.def viz_job(request):&nbsp; &nbsp; jobs = []&nbsp; &nbsp; descriziones = []&nbsp; &nbsp; posizione = Job.objects.all()&nbsp; &nbsp; for pos in posizione:&nbsp; &nbsp; &nbsp; &nbsp; jobs.append(pos.posizione)&nbsp; &nbsp; &nbsp; &nbsp; descriziones.append(pos.descrizione)&nbsp; &nbsp; context = {&nbsp; &nbsp; &nbsp; &nbsp; 'posizione': jobs,&nbsp; &nbsp; &nbsp; &nbsp; 'descrizione': descriziones&nbsp; &nbsp; }&nbsp; &nbsp; return render(request, 'jobs/jobs.html',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; context=context)&nbsp; # this will return context dictonary to the template您可以过滤并从数据库中获取特定数据
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python