【发布时间】: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>
{% 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