Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Template – Parent Detailview w/ child for loop list

I’ve been trying solutions that have been suggested for others in similar situations, however almost all questions are regarding bizzarely unusual scenarios and I’ve been unable to adapt them to my situation.

I’d like a for loop of child information in a parent’s DetailView

Models

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Projects(models.Model):
      fk_user = models.ForeignKey(User, on_delete=models.CASCADE)
      name = models.BooleanField(default=False)

class Projects_items(models.Model):
      itemName = models.BooleanField(default=False)
      fk_project = models.ForeignKey(Projects,on_delete=models.CASCADE, related_name="item")
      value = models.FloatField()

Views

class projects(LoginRequiredMixin, UserPassesTestMixin, UpdateView):

    model = Projects
    fields = [
    'name',
    ]
    template_name = 'games/project_details.html'
    context_object_name = 'projects'


    def form_valid(self, form):
        form.instance.fk_user = self.request.user
        form.save()
        # return super().form_valid(form)
        return HttpResponseRedirect(self.request.path_info)

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.fk_user:
            return True
        return False    

Template – projects_details

{% extends './underlay.html' %}
{% load static %}
{% load crispy_forms_tags %}
<link rel="stylesheet" type="text/css" href="{% static 'details.css' %}">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins">

{% block content %}
<H2>LIST OF ITEMS BELONGING TO THIS PROJECT</H2>
 
 ?

SOMETHING LIKE:
{% for projects.item in projects %}
{{ projects.item.itemName }} - {{ projects.item.value }}
{% endfor %}

THIS GAVE AN ERROR OF 'PROJECTS' OBJECT NOT ITERABLE

>Solution :

Firstfully, change name of classes to singular, like Project and Projects_item, because it’s confusing.

Secondly, change related_name of ForeignKey to related_name="items".

Then in template you can get all related Projects_items like this:

{% for item in project.items.all %}
    {{ item.itemName }} - {{ item.value }}
{% endfor %}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading