Home > database >  Django display data from two different models
Django display data from two different models

Time:06-14

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?

models.py

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/")

forms.py

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}),
        }

views.py

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)

projects.html

 {% for project in projects %}
          <div >
            <div >
                <img  src="{{project.image.url}}" alt="project thumbnail" />
                <div >
                  <h3>{{project.title}}</h3>
                  <h2>{{project.describtion}}</h2>
                </div>
              </a>
            </div>
          </div>
{% endfor %}

CodePudding user response:

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 
  <h3>{{project.title}}</h3>
  <h2>{{project.describtion}}</h2>
  {% for image in project.project_image_set.all %}
     {{ image.image }}
  {% endfor %}
</div>

Docs: https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_one/

CodePudding user response:

I don't really understand the question here but i see a problem in your template considering you are using foreign key in ProjectImage. And update the question

 {% for project in projects %}
          <div >
            <div >
               {% for j in project.projectimage_set.all %}
                <img  src="{{j.image.url}}" alt="project thumbnail" />
               {% endfor %}
                <div >
                  <h3>{{project.title}}</h3>
                  <h2>{{project.describtion}}</h2>
                </div>
              </a>
            </div>
          </div>
{% endfor %}

CodePudding user response:

I would change FileField to ImageField and add function:

@property
def get_photo_url(self):
    if self.image and hasattr(self.image, 'url'):
        return self.image.url
    else:
        return ''

If createProject function works( I would rename it to create_project) then in projects.html:

{% for project in projects %}
      <div >
        <div >
            <div >
              <h3>{{project.title}}</h3>
              <h2>{{project.describtion}}</h2>
              {% for img in project.projectimage_set.all %}

            <img  src="{{img.get_photo_url}}" alt="project thumbnail" />
              {% endfor %}
            </div>
          </a>
        </div>
      </div>

{% endfor %}

  • Related