djangoimportviewmodels

Django, viewing models from different app


I am super new to python programming and django and i got the basics out of the way. I created a project with two apps, home and video. In my video models.py i have the following data:

class Video(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField(blank=True, null=True)

I want to do something with this in my home app in the views.py, such as display the data in an html page and currently it is set up as followed:

from video.models import Video

def display_video(request):
    video_list = Video.objects.all()
    context = {'video_list': video_list}
    return render(request, 'home/home.html', context)

in my home.html

{% if video_list %}
 {% for video in video_list %}
  <p>{{ video.name }}</p>
  <p>{{ video.description }}</p>
 {% endfor %}
{% else %}
 <p>no videos to display</p>
{% endif %}

my home.html always returns "no videos to display"

But when i query Video.objects.all() in my video app it finds 2 objects. any help is appreciated.


Solution

  • I decided to delete the project and started over brand new but this time I used class views instead of function views. I'm not exactly sure why it didn't run but using class views it worked like a charm. So the equivalent in class views as simple as possible is.

     from video.models import Video
    
     class IndexView(generic.ListView):
       template_name = 'home/index.html'
       context_object_name = 'top_three'
    
       def get_queryset(self):
        return Video.objects.all()[:3]