在Django中使用模板实现视图

时间:2018-08-04 17:15:31

标签: django django-templates django-views

我正在努力在网页上显示从网站管理页面创建的一些模型对象。

我通过the relevant django tutorial page进行了梳理,但我尝试过的任何方法都无法在页面上显示模型对象。

这是我的模型。py:

from django.db import models
from datetime import datetime
from datetime import timedelta



# Create your models here.

def get_deadline():
    return datetime.today() + timedelta(days=3)

class JobPost(models.Model):
    created_at = models.DateTimeField(auto_now_add=True, blank=True)
    deadline = models.DateField(default=get_deadline)    
    wordcount = models.IntegerField()
    jobtaken = models.BooleanField(default=False)
    # client = models.User.username  

    class Meta:
        ordering = (
        # ("jobtaken"),
        ("-created_at"),
    )

    def publish(self):
        self.pub_date = timezone.now()
        self.save()

    def __str__(self):
        return "Job #{}".format(self.pk)`

views.py:

from django.shortcuts import render
from django.views.generic import TemplateView
#from django.contrib.auth.decorators import staff_member_required
from .models import JobPost
from django.utils import timezone
# Create your views here.

# @staff_member_required()
# class JobBoardView(TemplateView):
#      template_name = "jobs.html"
#      posts = JobPost.objects.filter(published_date__lte=timezone.now()).order_by('pub_date')

#changed published_date to pub_date in .models
def jobs(request):
    #posts = JobPost.objects.filter(published_date__lte=timezone.now()).order_by('published_date')

    latest_post_list = JobPost.objects.order_by('-pub_date')


    context = {

        'deadline': deadline,
        'created_at': created_at, 
        'wordcount':wordcount, 
        'jobtaken':jobtaken,
        'JobPost':JobPost,
        'latest_post_list':latest_post_list,
    }

    return render(request, 'jobs.html', context=context)

urls.py:

from django.contrib import admin
from django.urls import path, re_path, include
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from jobboard import views
from login import views

urlpatterns = [

    path('admin/', admin.site.urls),
    #re_path(r'^login/$', auth_views.login(template_name = 'accounts/login.html'), name='login'),
    re_path(r'^signup/$', views.signup, name='signup'),
    path('login/', include('login.urls')),
    path('', views.index, name='index'),
    path('accounts/', include('django.contrib.auth.urls')),
    path('users/', include('users.urls')),
    path('users/', include('django.contrib.auth.urls')),
    path('jobs/', views.jobs, name='jobs')
]

这是我的模板(jobs.html):

{% extends "base.html" %}

{% block content %}

  {% if latest_post_list %}
    <ul>
    {% for post in latest_post_list %}
        <li>{{ JobPost }}</li>
    {% endfor %} 
    </ul>
    {% else %}
    <p>No posts are available.</p>
 {% endif %}


{% endblock content %}

我尝试了各种模板,包括一些非常简单的模板,例如

  {% if latest_post_list %}
    <p>hello</p>
    {% else %}
    <p>No posts are available.</p>
 {% endif %}

但是我尝试的所有操作都会返回if语句的'else'部分。什么都不会在网页上显示对象。

2 个答案:

答案 0 :(得分:0)

您犯了一些错误,我将在下面列出:

  1. 您的查询方法错误。应该是:

    latest_post_list = JobPost.objects.all().order_by('-pub_date')

    latest_post_list = JobPost.objects.filter(something=something).order_by('-pub_date')


2. latest_post_list不是对象,它是对JobPost对象的查询。如果您希望在模板中对其进行迭代,则可以将其传递给模板并从查询中进行迭代。但是,

 context = {

    'deadline': deadline, # you cannot access deadline (which deadline?)
    'created_at': created_at, # same as above
    'wordcount':wordcount, # same as above
    'jobtaken':jobtaken, # same as above
    'JobPost':JobPost, # You are sending the class to the template which is wrong
    'latest_post_list':latest_post_list, # the only thing you need!
}
  1. 如果希望在后端循环浏览查询的对象,则必须执行以下操作:

    for post in latest_post_list:
        print(post.deadline) # will print the deadline of each JobPost one by one
    
  2. 如果要遍历查询对象并将其显示在模板中,则必须执行以下操作:

    {% for post in latest_post_list %}
        <p>{{ post.deadline }} - {{ post.created_at }}</p>
    {% empty %}
        <p>There is no post yet!</p>
    {% endfor %}
    


    无需在后端用户if或使用{{ JobPost }}。如果查询为空,则{% empty %}将有效。

答案 1 :(得分:0)

RoboBear是正确的,这是urls.py文件中的名称冲突。这修复了错误: 更改为from jobboard import views as job_views,并将网址行更改为path('jobs/', job_views.jobs, name='jobs')

对于

以外的所有上下文词典条目,在views.py文件中更改此引发的异常
    context = {

    'latest_post_list':latest_post_list,
}

如拉姆丁建议的那样。

然后我将模板更改为

    <ul>
     {% for post in latest_post_list %}
      <li>{{ post }}</li>
    </ul>
    {% empty %}
     <p>No posts are available.</p>

{% endfor %} 

如拉姆丁建议的那样。