A List inside a list in django templates - django

How do you render a list of user who have a list of their own objects related with foreign-key in Models. When I render in html it brings all list of all users in all users,
EDIT
Sorry for late reply, I rarely get time to get to my computer,
I have three models, Profile, Resume and Skills with the two related to Profile through foreign key...
VIEWS.PY
class ResumeList(ListView):
model = User_Profile
context_object_name = 'profile'
template_name = 'resume/list.html'
paginate_by = 6
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['resume'] = Resume.objects.all()
context['skill_list'] = Skill.objects.all()
return context
LIST.HTML
{% extends "base.html" %}
{% load static %}
{% block content %}
{% for obj in profile %}
{{ obj.first_name }}
{{ obj.last_name }}
{% for obj in resume %}
{{ obj.resume }}
{% endfor %}
{% for obj in skill_list %}
{{ obj.name }}
{% endfor %}
{% endfor %}
{% endblock %}
The Resume and Skill model loops are inside the profile loop but it displays all skills for all profiles...
When I change the get_context_data() to filter it brings error...
Thanks in advance...

Related

In which variable is the model instance stored in customized view?

How can I actually pick up values from my model in a customised template?
Let's assume for this example, the model for Request has an attribute "title".
Following views.py:
class RequestModelView(ModelView):
datamodel = SQLAInterface(Request)
extra_args = {'my_extra_arg':Request}
show_template = 'show_request.html'
list_columns = ['title','description','request_status']
and here the show_requests.html
{% extends "appbuilder/general/model/show.html" %}
{% block show_form %}
This Text is before the show widget
{{ super() }}
This Text is shown below..
<hr>
{{ (self.title) }}; {{pk}}; {{pk['title']}}
{% endblock %}
In which variable can I find my object?
The only parameter that works is {{pk}} (it shows the ID of the Request).
I was thinking of something like item['title']
Thanks.
A very similar question was asked on their Github. I think you would have to use something along these lines:
views.py
class RequestModelView(ModelView):
datamodel = SQLAInterface(Request)
list_columns = ['title','description','request_status']
add_template = 'show_request.html'
#expose('/show_request', methods=['GET', 'POST'])
#has_access
def show_request(self):
get_filter_args(self._filters)
self.extra_args = {'item': list_columns}
return super(RequestModelView, self).add()
show_requests.html:
{% extends "appbuilder/general/model/show.html" %}
{% block show_form %}
This Text is before the show widget
{{ super() }}
This Text is shown below..
<hr>
{{ item['title'] }}
{% endblock %}
Documentation is certainly not very clear in this aspect, but please check template-extra-arguments
I'm not sure if you would still need extra_args = {'my_extra_arg':Request}.
The following example should make things clear:
from .models import cars
beautiful_names = ["John", "Jane", "Bob"]
flowers = ["Aster", "Buttercup", "Roses"]
class IndexView(View):
template_name = "dashboard/dashboard_index.html"
def get(self, request, *args, **kwargs):
all_car_objects=cars.objects.all()
return render(request,
self.template_name,
context={"my_addresslist": beautiful_names,
"my_rose_list": roses},
"all_cars":all_car_objects)
In your template you can then do something like:
<h1>Beautiful Names</h1>
{% for name in my_addresslist %}
<p>{{ name }}</p>
{% endfor %}
<h1>Roses</>
{% if my_rose_list %}
{% for rose in my_rose_list %}
<p>{{ rose }}</p>
{% endfor %}
{% endif %}
<h1>Cars</>
{% if all_cars %}
{% for car in all_cars %}
<div>
<p>{{ car.name }}</p>
<p>{{ car.make }}</p>
<p>{{ car.model }}</p>
</div
{% endfor %}
{% endif %}
So for your example, it comes down to this:
class MyView(ModelView):
datamodel = SQLAInterface(MyTable)
extra_args = {'my_request_list':Request}
show_template = 'show_request.html'
<h1>Requests</>
{% if my_request_list %}
{% for request in my_request_list %}
<p>{{ request }}</p>
{% endfor %}
{% endif %}

I want to display User videos and Other's videos separately. I am not getting output from the following code, Is my approach correct?

My view goes something like this
class Test(ListView):
model = VideoUpload
template_name = 'videoTube/videoTube.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["my_video_list"] = VideoUpload.objects.filter(user=self.request.user)
context["other_video_list"] = VideoUpload.objects.exclude(user=self.request.user)
print(context)
return context
Template code
{% for vid in my_video_list %}
{% if forloop.counter < 5 %}
{{ vid.video }}
{% endif %}
{% endfor %}
{% for vid in other_video_list %}
{% if forloop.counter < 5 %}
{{ vid.video }}
{% endif %}
{% endfor %}
I am not getting anything in the output. I am expecting my_video_list and other_video_list should be displayed separately

Django template : {% if %} tag can't get it to work

I am looking for a way in order my templates can recognize an attribute from my extended userprofile, specifically if he is an affiliate and show different content in the templates whether he is an affiliate or not. Is there an other approach to this like to build an decorator?
i have worked with other {%if%} tags like this built-in auth request {% if request.user.is_authenticated %}
models.py project/useprofile/ , the book is in an other app project/book
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
affiliate = models.BooleanField(default=False)
add_book.html
{%extends 'base.html' %}
{% load i18n %}
{% load crispy_forms_tags %}
{% block content1 %}
{% if userprofile.profile.affiliate = True %}
<h1>New post</h1>
<form method="POST" class="post-form">
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="save btn btn-primary">Save</button>
</form>
{% endif %}
{% endblock %}
urls.py
url(r'^book/add/$', 'book.views.addbook', name='addbook'),
views.py
def addbook(request):
if request.method == "POST":
form = BookForm(request.POST)
if form.is_valid():
book = form.save(commit=False)
book.save()
return redirect('home')
else:
form = BookForm()
return render(request, 'add_book.html',
{'form':form,
})
UPDATE: i found a simple solution to my problem, just needed to put {% if user.profile.affiliate %} in my template since i have extended the django user profile and affiliate is boolean so i do not need do the equal == part since it passes if its True , but i am still looking for other options available

django view - all categories and all entries

I'm trying to build a page with all of the model's categories and associated entries in one view. I followed tips from here django class based views for all categories with all entires and here Get all categories and items in category but I still can't get it to work. Any ideas ?
-- models
class Category(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class Feed(models.Model):
name = models.CharField(max_length=100)
url = models.CharField(max_length=100)
category = models.ForeignKey(Category)
user = models.ManyToManyField(User)
def __unicode__(self):
return self.url
-- views
def category_page(request):
object_list = Category.objects.all()
context = {'object_list': object_list,}
return render(request, 'category_page.html', context)
-- template category_page.html
{% block content %}
{% for category in object_list %}
{{ category.name }}
{% for entry in category.entry_set.all %}
{{ category.name}}
{% endfor %}
{% endfor %}
{% endblock content %}
I'm getting list of all categories displayed but no entries.
thanks
-M
Here
{% for entry in category.entry_set.all %}
{{ category.name}}
{% endfor %}
should be
{% for entry in category.feed_set.all %}
{{ entry.name}}
{% endfor %}
{{ category.name}} inside the forloop for entries is what is not displaying the correct name.
Also, what is entry_set ? If you are not specifying a related_name, you need to use the lower-case model name to get the related objects (feed_set in this case).
Something like this:
category.feed_set.all
Summing it up,
{% block content %}
{% for category in object_list %}
{{ category.name }}
{% for entry in category.feed_set.all %}
{{ entry.name}}
{% endfor %}
{% endfor %}
{% endblock content %}
You can read more on related objects here
If this is your actual code, the problem is variable names in your template.
{% for category in object_list %}
{{ category.name }}
{% for entry in category.feed_set.all %}
{{ entry.name}}
{% endfor %}
{% endfor %}
Specifically, you refer to entry_set, but that's not the reverse name for the relationship since your model name is Feed rather than Entry and you haven't declared a non-default related_name argument.
Also, you're re-printing your category name instead of the name of the Feed instances.

Object not iterable with django's pagination

I have a template showing a list of events. To prepare list of events I'm using generic views, and set 'paginate_by' parameter. Strangely when I load my page I see :
TemplateSyntaxError at /event/latest/
Caught an exception while rendering: 'int' object is not iterable
in 9th line of pagination.html template :
{% if is_paginated %}
{% load i18n %}
<div class="pagination">
{% if page_obj.has_previous %}
<< Prev
{% else %}
<span class="disabled prev"><< Prev</span>
{% endif %}
#here {% for page in pages %}
{% if page %}
{% ifequal page page_obj.number %}
<span class="current page">{{ page }}</span>
{% else %}
{{ page }}
{% endifequal %}
{% else %}
...
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
Next >>
{% else %}
<span class="disabled next">Next >></span>
{% endif %}
</div>
{% endif %}
Here is my view :
def events_nearest(request):
events = Event.nearest.all()
return object_list(request,
queryset = events,
extra_context = {'title': 'Nearest events'},
paginate_by = 12,
template_name = 'event/events_date.html')
And model :
class NearestManager(models.Manager):
def get_query_set(self):
return super(NearestManager, self).get_query_set().order_by('-data')
class Event(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=120)
slug = models.SlugField(max_length=255, unique=True, verbose_name='Slug')
about = models.TextField()
city = models.ForeignKey(City)
objects = models.Manager()
nearest = NearestManager()
Any ideas what can cause this ?
pages variable is the number of pages, which is int and hence the error: 'int' object is not iterable
you should be looping over page_range
{% for page in page_range %}
I met the same error. There is a note at
https://docs.djangoproject.com/en/dev/topics/pagination/
Changed in Django Development version: Previously, you would need to use {% for contact in contacts.object_list %}, since the Page object was not iterable.
So {% for page in pages.object_list %} could probably solve your problem.
For anybody stumbled upon this post:
As with Django 1.4 and later (as far as I know), the iterable object for pagination is now paginator.page_range , i.e. the for loop should be
{% for page_num in paginator.page_range %}
In your error line #9 {% for page in pages %} what exactly is pages
Can't see it in your code anywhere.