Hi I'm new in Django and don't know how to get related objects with multiple models.
My code:
#models.py
class Candidate(models.Model):
user = models.OneToOneField(User, primary_key=True)
birth = models.CharField(max_length=50)
...
class CandidatePhotos(models.Model):
user = models.ForeignKey(User)
photo = models.ImageField(upload_to='usergallery/%Y/%m/%d')
class Job(models.Model):
candidate = models.ManyToManyField('Candidate', through='CandidateToJob')
title = models.CharField(max_length=500)
...
class CandidateToJob(models.Model):
job = models.ForeignKey(Job, related_name='applied_to')
candidate = models.ForeignKey(Candidate, related_name='from_user')
STATUS_CHOICES = (
('1', 'Not approved'),
('2', 'Approved'),
('3', 'Hired')
)
status = models.CharField(max_length=2, choices=STATUS_CHOICES)
In the views I have
#views.py
class CandidateDetails(generic.DetailView):
model = Candidate
template_name = 'dashboard/candidate.html'
def get_context_data(self, **kwargs):
context = super(CandidateDetails, self).get_context_data(**kwargs)
context['cand_photos'] = CandidatePhotos.objects.all()
return context
In the template I have
<h2>{{ candidate.user.first_name }} {{ candidate.user.last_name }}</h2>
{% for candidatephotos in cand_photos %}
<img alt="" src="{{ candidatephotos.photo.url }}" >
{% endfor %}
Here is my url dashboard/candidate/pk/.
What happens is in the template all users photos are loaded instead of only the specific user I want. I have tried to get the user photos using {{ candidate.user.candidatephotos_set.photo.url }} but it doesn't work.
I have also tried to change in views.py the model from "Candidate" to "CandidateToJob" (the through model) but I get a 404 error, I don't know why.
So, what is the best practice to achieve this?