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
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
CodePudding user response:
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 %}