Answer the question
In order to leave comments, you need to log in
How to print model or model form with all related tables in Django?
Good day.
The same problem has been tormenting me for a day now. The model has the properties of my object, how to display it in text form in the DetailView, like a table.
What I tried: I couldn't loop through the response object. Throws an error Object no iterable.
The object.filter().values() option does not suit me, since in my table it is mainly through foreign keys and they are displayed as pk. And I need to display not the primary key, but the value, and I still couldn’t take the verbose_name value there.
I tried to pervert using self-written filters in the template, but it did not give the desired result.
My only hook is the ModelForm, but it produces selects and inputs. Widgets have not been written before.
What options can be seen.
Before that I wrote in php.
Answer the question
In order to leave comments, you need to log in
Perhaps the following method will work.
In the view, the advert_fields variable is added to the context:
class AdvertDetailView(DetailView):
model = Advert
template_name = "advert/_detail.html"
context_object_name = "advert"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
advert_fields = []
for field in self.model._meta.fields:
advert_fields.append((field.verbose_name, str(getattr(self.object, field.name))))
context['advert_fields'] = advert_fields
return context
<ul>
{% for verbose_name, value in advert_fields %}
<li>{{ verbose_name }} -> {{ value }}</li>
{% endfor %}
</ul>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question