Reputation: 3262
I have customuser model name Profile and VideoFile models with relative fields to User. There are many users account and each of them can add a lot of video files. I need to show at templates.html user.nickname and all of him videofiles.
user.models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
nickname = models.CharField(max_length=30, blank=True, verbose_name="Никнэйм")
userpic = models.ImageField(upload_to='userpics/', blank=True, null=True)
videofile.models.py
class VideoFile(models.Model):
name = models.CharField(max_length=200,blank=True)
file = models.FileField(upload_to="vstories/%Y/%m/%d", validators=[validate_file_extension])
date_upload = models.DateTimeField(auto_now_add = True, auto_now = False, blank=True, null = True)
descriptions = models.TextField(max_length=200)
reports = models.BooleanField(default=False)
vstories = models.ForeignKey(Profile, blank = True, null = True)
views.py
def vstories (request):
profiles = Profile.objects.all()
return render(request, "vstories/vstories.html", {'profiles':profiles})
templates.html
{% extends "base.html" %}
{% block content %}
{% if users %}
{% for user in users %}
<p>{{ user.profile.nickname}}</p>
{% for vstorie in vstories %}
<p>{{ vstorie.vstories.url }}</p>
{% endfor %}
{% endfor %}
{% endif %}
{% endblock content %}
With the video, I'm confused. Or maybe I chose the wrong way to communicate models?
Upvotes: 1
Views: 45
Reputation: 1110
You can look for the foreign keys "backward". In this case, to access to all videos of a user (Profile), you need to have all Profiles:
def vstories (request):
profiles = Profile.objects.all()
return render(request, "vstories/vstories.html",{'profiles':profiles})
Then, in the template, you can access the relationship between Profile and VideoFile "backward".
{% for profile in profiles %}
{% for videofile in profile.videofile_set.all %}
<p>{{ videofile.file.url }}</p>
{% endfor %}
{% endfor %}
The trick is in the "_set" that allows you to follow the relationship backward.
Here is the documentation for this kind of queryset: https://docs.djangoproject.com/en/2.0/topics/db/queries/#following-relationships-backward
Upvotes: 1
Reputation: 3262
This work for me
{% for profile in profiles %}
{{ profile.nickname }}
{% for videofile in profile.videofile_set.all %}
<video width="320" height="240" controls src="{{ videofile.file.url }}">
Your browser does not support the video tag.
</video>
{% endfor %}
{% endfor %}
Upvotes: 1