You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:Django视图实现近1小时帖子JSON导出至HTML页面问题

Hey Davide, let's fix up your code to get it working exactly as you want—grabbing the last hour's posts, structuring their data properly, and displaying them nicely in HTML. Here's what's going wrong right now, plus the corrected code:

Issues in Your Current Code

  • Overwriting Post Data: You're using a single post_detail dictionary, so every loop iteration replaces the previous post's data. You need a list to store all posts instead.
  • Incorrect JSON Usage: json.dump() requires a file-like object to write to. To convert your data to a usable format for the template, you should either pass the list of post dictionaries directly, or use json.dumps() if you specifically need a JSON string.
  • Timezone Mismatch: You're using a naive now() but your model uses timezone-aware timezone.now(). This can cause filtering inconsistencies—stick with timezone.now() for consistency.
  • Template Doesn't Render Post Details: Right now you're just dumping a raw JSON string, but you want to display each post's author, title, and content individually.

Corrected Code

Updated views.py

from django.utils import timezone
from datetime import timedelta
from django.contrib.auth.decorators import superuser_only
from .models import Post
from django.shortcuts import render

@superuser_only
def PostUltimaOra(request):
    # Initialize a LIST to store all post data (not a single dictionary)
    post_details = []
    current_time = timezone.now()
    
    # Filter posts from the last hour using timezone-aware datetimes
    posts_last_hour = Post.objects.filter(
        published_date__range=(current_time - timedelta(hours=1), current_time)
    )
    
    for post in posts_last_hour:
        post_details.append({
            'author': post.author.username,  # Use username for readable display
            'title': post.title,
            'text': post.text,
            # Format datetime into a human-readable string
            'published_date': post.published_date.strftime("%Y-%m-%d %H:%M:%S")
        })
    
    # Pass the list of posts directly to the template
    return render(request, 'blog/numeroposts.html', {'posts_last_hour': post_details})

Updated Template (numeroposts.html)

{% extends 'blog/base.html' %}
{% block content %}
<h1>Posts pubblicati nell'ultima ora</h1>

{% if posts_last_hour %}
    {% for post in posts_last_hour %}
        <div style="margin-bottom: 2rem; padding: 1rem; border: 1px solid #eee; border-radius: 4px;">
            <h2>{{ post.title }}</h2>
            <p><strong>Autore:</strong> {{ post.author }}</p>
            <p><strong>Data di pubblicazione:</strong> {{ post.published_date }}</p>
            <div>
                {{ post.text|linebreaksbr }}
            </div>
        </div>
    {% endfor %}
{% else %}
    <p>Nessun post pubblicato nell'ultima ora.</p>
{% endif %}
{% endblock %}

Quick Note on models.py

Your Post model is already set up correctly! Just ensure you always call the publish() method to set published_date (instead of setting it manually) to keep timezone consistency.

内容的提问来源于stack exchange,提问作者Davide Maisano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 20:58:11