【问题标题】:data doesn't appear in my html page when i add new record - Django当我添加新记录时,数据没有出现在我的 html 页面中 - Django
【发布时间】:2020-11-01 20:41:31
【问题描述】:

当我从admin panel 添加新记录时,它应该出现在 html 页面中,但它没有这样做

如何解决

models.py:

class BestArticals(models.Model):
    name = models.CharField(max_length=240)
    url = models.URLField(default="",max_length=240)
    image = models.ImageField(upload_to='images/',null=True, blank=True)

    def get_image(self):
        if self.image and hasattr(self.image, 'url'):
            return self.image.url
        else:
            return '/path/to/default/image'

    def __str__(self):
        return self.name

views.py:

from .models import BestArticals

def Best_Articals(request):
    best_posts = BestArticals.objects.all()
    context = {'best_posts' : best_posts}
    return render(request,'android/side_bar_good_posts.html',context=context)

html页面:

  {% for post in best_posts %}

  <div class="card rounded mx-auto d-block" style="width: 18rem;margin-bottom:50px;border-color:#7952b3">
    
  <div class="card-body" id="mobile_design_card">
    <a href="{{post.url}}"><p class="card-text" id="mobile_design_card_name">{{ post.name }}</p></a>
  </div>
  <a href="{{post.url}}"><img src="{{ post.get_image }}" class="card-img-top" alt="..." height="290px" width="300px"></a>

  </div>
&nbsp;&nbsp;
  {% endfor %}
  • 我没有在 urls.py 中添加Best_Articals,因为我不想为其创建 url,我只想在来自side_bar_good_posts.html 的其他 html 页面中显示数据

例如,我在其他 html 页面中添加了这一行:

{% include 'android/side_bar_good_posts.html' %}

【问题讨论】:

  • 刷新页面时会发生什么?您如何尝试显示数据?
  • 当我刷新页面时没有任何反应
  • 我尝试过我的代码..我不知道是什么问题...当我为页面设置 url 时它正常显示数据但是当我在其他 html 页面中使用它时,如 {% include 'test.html' %} 它不起作用

标签: django django-models django-views django-templates


【解决方案1】:

根据您上次的评论...您应该分析包含标签查看功能的工作原理。让我试着解释一下,当您向某个 url 发出请求时,它会调用特定的 view 函数,并且视图会在您设置 url 时返回处理后的数据。 包含标签只在你使用包含标签的文件中添加其中的所有文本,为此当你添加include 'android/side_bar_good_posts.html'时只添加纯文本(html、css、js ) 包含 android/side_bar_good_posts.html 但此时此文件不包含有关帖子的信息,因为您的变量 best_posts 为空,没有调用您的 Best_Articals 视图返回 best_post。您需要将附加上下文 (best_post) 传递给您的模板。 IE。 {% include "name_snippet.html" with person="Jane" greeting="Hello" %}

或者您可以使用上下文处理器,然后您可以在所有模板中使用 {{best_post}}。

【讨论】:

  • 感谢您的评论 .. 你能解释更多关于这一行的信息吗... {% include "name_sn-p.html" with person="Jane" greeting="Hello" %} ... . 在我的情况下,我应该在后面写什么 .. 我的意思是什么是人和问候
  • person 和 getting 是您可以在模板中读取的变量({{person}}、{{greeting}})。在您的情况下,您应该在“with”之后通过 best_posts = best_posts
  • 我试过这样{% include "android/side_bar_good_posts.html" with best_posts=best_posts %}但它不起作用
  • 你得到 best_post 的价值了吗?您需要先获取值,类似于best_posts = BestArticals.objects.all(),然后在包含标记中使用 with 传递 best_post
  • 如果我为它设置 url 并打开浏览器然后打开 url 是的我得到了我的数据但是当我使用 {%include%} 时它不会加载 for 循环
猜你喜欢
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-15
  • 2016-01-18
  • 1970-01-01
相关资源
最近更新 更多