Access date_subscribed from a many to many field on a for loop template Django

477 views Asked by At

I have these models,

class Place(models.Model):
   name = models.CharField(max_length=200)
   user = models.ForeignKey(User, on_delete=models.CASCADE, 
   related_name='places', default=1)
   subscribers = models.ManyToManyField(AppUser, through='PlaceSubscriber')
   def __str__(self):              # __unicode__ on Python
       return self.name

class PlaceSubscriber(models.Model):
    place = models.ForeignKey(Place, on_delete=models.CASCADE)
    user = models.ForeignKey(AppUser, on_delete=models.CASCADE)
    date_subscribed = models.DateTimeField(editable=False, default=timezone.now)

    class Meta:
        unique_together = ('place', 'user')

I want to access the date_subscribed fields on this for loop inside my template

{% for o in place.subscribers.all %}
    <a href="#" class="list-group-item clearfix">
    <span class="pull-left">
         {{ forloop.counter }}. &emsp;
    </span>
    <span class="pull-left">
         <strong>{{ o.full_name }}</strong>
         <p>Email: <i>{{ o.email }}</i> | Date Subscribed: <i> {{ 
          o.place__placesubscriber__date_subscribed }} </i> </p>
    </span>
    <span class="pull-right">
    <span class="btn btn-xs btn-primary" 
       onclick="sendPushNotificationToUser('{{ o.ionic_id }}'); return 
       false;">Send Message</span>
    <span class="btn btn-xs btn-danger" onclick="deletePlaceUser({{ place.id 
        }}, {{ o.id }}); return false;  ">
      Unsubscribe
   </span>

   </button>
   </span>
   </a>
{% endfor %}

I can access the date_subscribed field outside this foorloop like this:

{% for each in place.placesubscriber_set.all %}
    {{ each.date_subscribed }}
{% endfor %}

But havenĀ“t figure out how to it access inside the other one.

UPDATE

This is my view

class PlaceDetailView(DetailView):
    model = Place
    template_name = 'place/place_detail.html'

And this is the url pattern

url(r'^place/(?P<pk>\d+)$', views.PlaceDetailView.as_view(), name='detail_place'),
3

There are 3 answers

0
Alex On BEST ANSWER

I usually try to make a good query to deal with simple data structure in my template, avoiding complicated logic.

I would replace the view for a simple one that makes the query that you want (hopefully):

def place_detail(request):

    data = PlaceSubscriber.objects.all().values(
        'user__full_name',
        'user__email',
        'place__name',
        'date_subscribed'
    )

    return render(request,'place.html',{'data':data})

This generates a list of dictionaries with the query keys. You can display this data now by:

{% for el in data %}
    {el.user__full_name}
    {el.date_subscribed}
    ...
{% endfor %}

Well, I'm not sure if is that you want, but you can change the query values to get exactly what you want.

Hope it helps.

0
Parias Lunkamba Mukeba On

i think in your views.py file you should do this:

from django.shortcuts import render
from .models import Place
def placeview(request):
    place = Place()
    return render(request, 'place.html', {'place':place})
0
Mario Zepeda On

I Ended up following @Tico approach,I updated my view so it had less logic than before, this was my update:

Updated my urls.py file, stopped using generic Detail view Class

url(r'^place/(?P<place_id>\d+)$', views.place_detail, name='detail_place'),

Updated the detail view method on views.py file to return the data I need from both models:

def place_detail(request, place_id):
    place = get_object_or_404(Place, pk=place_id)
    placeSubscribers = PlaceSubscriber.objects.all().filter(place=place).values(
         'user__full_name',
         'user__email',
         'user__ionic_id',
         'place__name',
         'date_subscribed',
         'pk'
     )
     return render(request, 'place/place_detail.html', {'place': place, 'placeSubscribers': placeSubscribers}) 

Anda Finally updated my template For to pull the data from placeSubscribers, there I can access the date_subscribed field

 {% for placeSubscriber in placeSubscribers %}
      <a href="#" class="list-group-item clearfix">
        <span class="pull-left">
          {{ forloop.counter }}. &emsp;
        </span>
        <span class="pull-left">
        <strong>{{ placeSubscriber.user__full_name }}</strong>
         <p>Email: <i>{{ placeSubscriber.user__email }}</i> | Date Subscribed: <i> {{ placeSubscriber.date_subscribed }} </i> </p>
        </span>
        <span class="pull-right">
          <span class="btn btn-xs btn-primary" onclick="sendPushNotificationToUser('{{ placeSubscriber.user__ionic_id }}'); return false;">Send Message</span>
         <span class="btn btn-xs btn-danger" onclick="deletePlaceUser({{ place.id }}, {{ placeSubscriber.pk }}); return false;  ">
           Unsubscribe
           </span>
          </button>
         </span>
         </a>
{% endfor %}