Django display data from two different models

I have two seperated models. One with two text fields and one for multiple images. Now I want to display the entire data in one html div. What do I have to change in the projects view and in projects.html?

class Project(models.Model):
    title = models.CharField(max_length=200)
    describtion = models.TextField(null=True, blank=True)

class ProjectImage(models.Model):
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    image = models.FileField(upload_to="products/")

class ProjectForm(forms.ModelForm):
    class Meta:
        model = Project
        fields = ['title', 'describtion']

class ProjectImageForm(forms.ModelForm):
    class Meta:
        model = ProjectImage
        fields = ['image']
        widgets = {
            'image': ClearableFileInput(attrs={'multiple': True}),

def createProject(request):
    form = ProjectForm()
    form2 = ProjectImageForm()

    if request.method == 'POST':
        form = ProjectForm(request.POST)
        form2 = ProjectImageForm(request.POST, request.FILES)
        images = request.FILES.getlist('image')
        if form.is_valid() and form2.is_valid():
            title = form.cleaned_data['title']
            describ = form.cleaned_data['describtion']
            project_instance = Project.objects.create(
                title=title, describtion=describ)
            for i in images:
                ProjectImage.objects.create(project=project_instance, image=i)

    context = {'form': form, 'form2': form2}
    return render(request, 'projects/project_form.html', context)

def projects(request):
    projects = Project.objects.all()
    context = {"projects":projects}
    return render(request, 'projects/projects.html', context)


 {% for project in projects %}
          <div class="column">
            <div class="card project">
                <img class="project__thumbnail" src="{{project.image.url}}" alt="project thumbnail" />
                <div class="card__body">
{% endfor %}

>Solution :

You don’t need to change anything.

You should be able to access the reverse with project.project_image_set attribute in the template:

<div class="card__body"
  {% for image in project.project_image_set.all %}
     {{ image.image }}
  {% endear %}


Leave a Reply