data doesn't appear in my html page when i add new record - Django

旧街凉风 提交于 2020-12-15 06:26:13

问题


when i add new record from admin panel it should appear in html page , but it doesn't do that

how to fix it

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 page :

  {% 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 %}
  • i didn't add Best_Articals in urls.py because i don't want create url for it , i just want show data in other html page from side_bar_good_posts.html

for example i add this line in other html page :

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

回答1:


Based on your last comment... You should analyze how to works include tag and view function. Let me try to explain me, when you make request to some url, it calls to specific view function and the view return the processed data for this reason when you set url it works. Include tag only add all text from in it in your file where you use include tag, for this when you add include 'android/side_bar_good_posts.html' only add plain text (html, css, js ) that contains android/side_bar_good_posts.html but in this point this file doesn't contains information about the post because your variable best_posts is empty, nothing call to your Best_Articals view to return best_post. You need to pass the additional context (best_post) to your template. I.e. {% include "name_snippet.html" with person="Jane" greeting="Hello" %}

Or you could use context processor and then you can use {{best_post}} in all the templates.



来源:https://stackoverflow.com/questions/64636761/data-doesnt-appear-in-my-html-page-when-i-add-new-record-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!