Question

this question extends Django Pass Multiple Models to one Template

In that I want to produce 1 template, that is my profile index page, so it will list all the objects created by the user specified in the url

I want to query multiple models for one template, get the Profile in question and show all the oferto objects that was created by the attached profile

views.py

class ProfileIndex(ListView):
context_object_name = 'account_list'    
template_name = 'profiles/account_index.html'
queryset = Profile.objects.all()

def get_context_data(self, **kwargs):
    context = super(ProfileIndex, self).get_context_data(**kwargs)
    context['profile'] = Profile.objects.all()
    context['oferto'] = Oferto.objects.get(kwargs.profile.slug)

    return context

urls.py I am thinking I need to get the profile slug from the url in order to search for all oferto by that user in the url

url(
regex=r"^index/(?P<slug>[-_\w]+)",
view=ProfileIndex.as_view(),
name="profile_index",
),

And this has been the hardest to figure out, how to make my template work correctly from the context in question

{% block content %}

<h1>{{ profile }}<h1>
    <h2> Ofertoj or/aŭ Offers</h2>
    {% for oferto in profile  %}
        <a href="{% url "oferto_detail" oferto.slug %}">{{ oferto.name }}</a><br/>


    {% endfor %}




{% endblock %}
Était-ce utile?

La solution

frontend/models.py

Class Profile(models.Model):
   ....

Class Oferto(models.Model): 
   profile = model.ForeignKey(Profile):
   ...

frontend/views.py

Class ViewProfileList(ListView):
    model = Profile
    template_name = 'frontend/view_profile_list.html'

frontend/templates/frontend/view_profile_list.html

  {% for profile in object_list.all %}
      {% for ofer in profile.oferto_set.all %}
         {{ ofer.you_field }}
      {% endfor %}
  {% endfor %} 

Autres conseils

You don't state what your problem is exactly. But there are two issues with the syntax you're using in the query of Oferto: first, kwargs is a dictionary which has a "slug" key (no idea why you've put profile in there), and secondly you need to provide a field name to query against.

It should be:

context['oferto'] = Oferto.objects.get(slug=kwargs['slug'])
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top