nested for loops inside templates
models.py
class Task(models.Model):
level = models.ForeignKey(Level, on_delete=models.CASCADE)
todo = models.ForeignKey(ToDo, on_delete=models.CASCADE)
student = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=150)
content = models.TextField()
timestamp = models.TimeField(auto_now=True)
datestamp = models.DateField( auto_now=True)
like = models.ManyToManyField(User,related_name='user_likes', blank=True)
is_verified=models.BooleanField(default=False, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('student:task-detail', kwargs='pk': self.pk)
objects = PostManager()
@property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
@property
def get_content_type(self):
instance = self
content_type = ContentType.objects.get_for_model(instance.__class__)
return content_type
class Images(models.Model):
post = models.ForeignKey(Task, default=None,on_delete=models.CASCADE)
image = models.ImageField(verbose_name='Image',blank=True)
def __str__(self):
return self.post.title
I have two models Task and Images. Im storing multiple images for a task saved . I want to display the list of tasks using pagination and also images inside each task.
views.py:
@login_required(login_url='/account/login/')
@page_template('student_dash_page.html')
def StudentDashView(request,template='student_dash.html', extra_context=None):
if not request.user.is_authenticated:
return redirect('accounts:index')
task = Task.objects.all().order_by('timestamp')
images = Images.objects.filter(post=task)
notifications = Notification.objects.filter(receiver=request.user).order_by('-timestamp')
page = request.GET.get('page', 1)
paginator = Paginator(task, 10)
try:
tasks = paginator.page(page)
except PageNotAnInteger:
tasks = paginator.page(1)
except EmptyPage:
tasks= paginator.page(paginator.num_pages)
context =
'notifications': notifications,
'nbar': 'home',
'task': tasks,
'images': images
if not request.user.is_client:
return HttpResponse("You are in trainer account")
if extra_context is not None:
context.update(extra_context)
return render(request, template, context)
How do i get the images to display correctly inside the template using for loops
Im trying
% for obj in task %
<p> obj.title
% for image in images %
<img src=" image.url "</img>
% endfor %
% endfor %
Im getting the error: The QuerySet value for an exact lookup must be limited to one result using slicing.
python django
add a comment |
models.py
class Task(models.Model):
level = models.ForeignKey(Level, on_delete=models.CASCADE)
todo = models.ForeignKey(ToDo, on_delete=models.CASCADE)
student = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=150)
content = models.TextField()
timestamp = models.TimeField(auto_now=True)
datestamp = models.DateField( auto_now=True)
like = models.ManyToManyField(User,related_name='user_likes', blank=True)
is_verified=models.BooleanField(default=False, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('student:task-detail', kwargs='pk': self.pk)
objects = PostManager()
@property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
@property
def get_content_type(self):
instance = self
content_type = ContentType.objects.get_for_model(instance.__class__)
return content_type
class Images(models.Model):
post = models.ForeignKey(Task, default=None,on_delete=models.CASCADE)
image = models.ImageField(verbose_name='Image',blank=True)
def __str__(self):
return self.post.title
I have two models Task and Images. Im storing multiple images for a task saved . I want to display the list of tasks using pagination and also images inside each task.
views.py:
@login_required(login_url='/account/login/')
@page_template('student_dash_page.html')
def StudentDashView(request,template='student_dash.html', extra_context=None):
if not request.user.is_authenticated:
return redirect('accounts:index')
task = Task.objects.all().order_by('timestamp')
images = Images.objects.filter(post=task)
notifications = Notification.objects.filter(receiver=request.user).order_by('-timestamp')
page = request.GET.get('page', 1)
paginator = Paginator(task, 10)
try:
tasks = paginator.page(page)
except PageNotAnInteger:
tasks = paginator.page(1)
except EmptyPage:
tasks= paginator.page(paginator.num_pages)
context =
'notifications': notifications,
'nbar': 'home',
'task': tasks,
'images': images
if not request.user.is_client:
return HttpResponse("You are in trainer account")
if extra_context is not None:
context.update(extra_context)
return render(request, template, context)
How do i get the images to display correctly inside the template using for loops
Im trying
% for obj in task %
<p> obj.title
% for image in images %
<img src=" image.url "</img>
% endfor %
% endfor %
Im getting the error: The QuerySet value for an exact lookup must be limited to one result using slicing.
python django
Please show the full traceback. And you don't seem to be using formsets at all - where are they?
– Daniel Roseman
Oct 25 '18 at 8:23
Im using formsets as to save the models when submitting the form.This is for displaying.The images are saving correctly! @DanielRoseman
– Mohit Harshan
Oct 25 '18 at 8:26
But you mentioned formsets twice, and I don't understand how they are relevant to your question. You still need to show the traceback.
– Daniel Roseman
Oct 25 '18 at 8:27
sorry for confusing.Edited! @DanielRoseman
– Mohit Harshan
Oct 25 '18 at 8:28
add a comment |
models.py
class Task(models.Model):
level = models.ForeignKey(Level, on_delete=models.CASCADE)
todo = models.ForeignKey(ToDo, on_delete=models.CASCADE)
student = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=150)
content = models.TextField()
timestamp = models.TimeField(auto_now=True)
datestamp = models.DateField( auto_now=True)
like = models.ManyToManyField(User,related_name='user_likes', blank=True)
is_verified=models.BooleanField(default=False, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('student:task-detail', kwargs='pk': self.pk)
objects = PostManager()
@property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
@property
def get_content_type(self):
instance = self
content_type = ContentType.objects.get_for_model(instance.__class__)
return content_type
class Images(models.Model):
post = models.ForeignKey(Task, default=None,on_delete=models.CASCADE)
image = models.ImageField(verbose_name='Image',blank=True)
def __str__(self):
return self.post.title
I have two models Task and Images. Im storing multiple images for a task saved . I want to display the list of tasks using pagination and also images inside each task.
views.py:
@login_required(login_url='/account/login/')
@page_template('student_dash_page.html')
def StudentDashView(request,template='student_dash.html', extra_context=None):
if not request.user.is_authenticated:
return redirect('accounts:index')
task = Task.objects.all().order_by('timestamp')
images = Images.objects.filter(post=task)
notifications = Notification.objects.filter(receiver=request.user).order_by('-timestamp')
page = request.GET.get('page', 1)
paginator = Paginator(task, 10)
try:
tasks = paginator.page(page)
except PageNotAnInteger:
tasks = paginator.page(1)
except EmptyPage:
tasks= paginator.page(paginator.num_pages)
context =
'notifications': notifications,
'nbar': 'home',
'task': tasks,
'images': images
if not request.user.is_client:
return HttpResponse("You are in trainer account")
if extra_context is not None:
context.update(extra_context)
return render(request, template, context)
How do i get the images to display correctly inside the template using for loops
Im trying
% for obj in task %
<p> obj.title
% for image in images %
<img src=" image.url "</img>
% endfor %
% endfor %
Im getting the error: The QuerySet value for an exact lookup must be limited to one result using slicing.
python django
models.py
class Task(models.Model):
level = models.ForeignKey(Level, on_delete=models.CASCADE)
todo = models.ForeignKey(ToDo, on_delete=models.CASCADE)
student = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=150)
content = models.TextField()
timestamp = models.TimeField(auto_now=True)
datestamp = models.DateField( auto_now=True)
like = models.ManyToManyField(User,related_name='user_likes', blank=True)
is_verified=models.BooleanField(default=False, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('student:task-detail', kwargs='pk': self.pk)
objects = PostManager()
@property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
@property
def get_content_type(self):
instance = self
content_type = ContentType.objects.get_for_model(instance.__class__)
return content_type
class Images(models.Model):
post = models.ForeignKey(Task, default=None,on_delete=models.CASCADE)
image = models.ImageField(verbose_name='Image',blank=True)
def __str__(self):
return self.post.title
I have two models Task and Images. Im storing multiple images for a task saved . I want to display the list of tasks using pagination and also images inside each task.
views.py:
@login_required(login_url='/account/login/')
@page_template('student_dash_page.html')
def StudentDashView(request,template='student_dash.html', extra_context=None):
if not request.user.is_authenticated:
return redirect('accounts:index')
task = Task.objects.all().order_by('timestamp')
images = Images.objects.filter(post=task)
notifications = Notification.objects.filter(receiver=request.user).order_by('-timestamp')
page = request.GET.get('page', 1)
paginator = Paginator(task, 10)
try:
tasks = paginator.page(page)
except PageNotAnInteger:
tasks = paginator.page(1)
except EmptyPage:
tasks= paginator.page(paginator.num_pages)
context =
'notifications': notifications,
'nbar': 'home',
'task': tasks,
'images': images
if not request.user.is_client:
return HttpResponse("You are in trainer account")
if extra_context is not None:
context.update(extra_context)
return render(request, template, context)
How do i get the images to display correctly inside the template using for loops
Im trying
% for obj in task %
<p> obj.title
% for image in images %
<img src=" image.url "</img>
% endfor %
% endfor %
Im getting the error: The QuerySet value for an exact lookup must be limited to one result using slicing.
python django
python django
edited Oct 25 '18 at 8:28
Mohit Harshan
asked Oct 25 '18 at 8:18
Mohit HarshanMohit Harshan
1329
1329
Please show the full traceback. And you don't seem to be using formsets at all - where are they?
– Daniel Roseman
Oct 25 '18 at 8:23
Im using formsets as to save the models when submitting the form.This is for displaying.The images are saving correctly! @DanielRoseman
– Mohit Harshan
Oct 25 '18 at 8:26
But you mentioned formsets twice, and I don't understand how they are relevant to your question. You still need to show the traceback.
– Daniel Roseman
Oct 25 '18 at 8:27
sorry for confusing.Edited! @DanielRoseman
– Mohit Harshan
Oct 25 '18 at 8:28
add a comment |
Please show the full traceback. And you don't seem to be using formsets at all - where are they?
– Daniel Roseman
Oct 25 '18 at 8:23
Im using formsets as to save the models when submitting the form.This is for displaying.The images are saving correctly! @DanielRoseman
– Mohit Harshan
Oct 25 '18 at 8:26
But you mentioned formsets twice, and I don't understand how they are relevant to your question. You still need to show the traceback.
– Daniel Roseman
Oct 25 '18 at 8:27
sorry for confusing.Edited! @DanielRoseman
– Mohit Harshan
Oct 25 '18 at 8:28
Please show the full traceback. And you don't seem to be using formsets at all - where are they?
– Daniel Roseman
Oct 25 '18 at 8:23
Please show the full traceback. And you don't seem to be using formsets at all - where are they?
– Daniel Roseman
Oct 25 '18 at 8:23
Im using formsets as to save the models when submitting the form.This is for displaying.The images are saving correctly! @DanielRoseman
– Mohit Harshan
Oct 25 '18 at 8:26
Im using formsets as to save the models when submitting the form.This is for displaying.The images are saving correctly! @DanielRoseman
– Mohit Harshan
Oct 25 '18 at 8:26
But you mentioned formsets twice, and I don't understand how they are relevant to your question. You still need to show the traceback.
– Daniel Roseman
Oct 25 '18 at 8:27
But you mentioned formsets twice, and I don't understand how they are relevant to your question. You still need to show the traceback.
– Daniel Roseman
Oct 25 '18 at 8:27
sorry for confusing.Edited! @DanielRoseman
– Mohit Harshan
Oct 25 '18 at 8:28
sorry for confusing.Edited! @DanielRoseman
– Mohit Harshan
Oct 25 '18 at 8:28
add a comment |
1 Answer
1
active
oldest
votes
This line doesn't make any sense:
images = Images.objects.filter(post=task)
because task
is a queryset of all the Task instances.
You don't need to get the images at all in the view. Remove that line and the other references, and just do this in the template:
% for obj in task %
<p> obj.title </p>
% for image in obj.images_set.all %
<img src=" image.image.url "</img>
% endfor %
% endfor %
Note also, the Image object has a field called image
, and that's what you need to access the url attribute on.
(For the sake of database efficiency, you might want to change your query slightly in the view:
task = Task.objects.all().order_by('timestamp').prefetch_related('images_set')
otherwise every iteration will cause a separate db call to get the related images. You don't need to do this to make things work, though.)
Cannot find 'images' on Task object, 'images' is an invalid parameter to prefetch_related()
– Mohit Harshan
Oct 25 '18 at 8:38
Are you sure you have posted the correct models? That would work given what you have shown above. Could the model actually be calledImage
rather thanImages
? Does it work without the prefetch_related?
– Daniel Roseman
Oct 25 '18 at 8:43
It is also not pulling any images
– Mohit Harshan
Oct 25 '18 at 8:43
It is not working without prefetch_related . The models are correct
– Mohit Harshan
Oct 25 '18 at 8:44
fixed the issue . It should be % for image in obj.images_set.all %
– Mohit Harshan
Oct 25 '18 at 8:47
|
show 3 more comments
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52984538%2fnested-for-loops-inside-templates%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
This line doesn't make any sense:
images = Images.objects.filter(post=task)
because task
is a queryset of all the Task instances.
You don't need to get the images at all in the view. Remove that line and the other references, and just do this in the template:
% for obj in task %
<p> obj.title </p>
% for image in obj.images_set.all %
<img src=" image.image.url "</img>
% endfor %
% endfor %
Note also, the Image object has a field called image
, and that's what you need to access the url attribute on.
(For the sake of database efficiency, you might want to change your query slightly in the view:
task = Task.objects.all().order_by('timestamp').prefetch_related('images_set')
otherwise every iteration will cause a separate db call to get the related images. You don't need to do this to make things work, though.)
Cannot find 'images' on Task object, 'images' is an invalid parameter to prefetch_related()
– Mohit Harshan
Oct 25 '18 at 8:38
Are you sure you have posted the correct models? That would work given what you have shown above. Could the model actually be calledImage
rather thanImages
? Does it work without the prefetch_related?
– Daniel Roseman
Oct 25 '18 at 8:43
It is also not pulling any images
– Mohit Harshan
Oct 25 '18 at 8:43
It is not working without prefetch_related . The models are correct
– Mohit Harshan
Oct 25 '18 at 8:44
fixed the issue . It should be % for image in obj.images_set.all %
– Mohit Harshan
Oct 25 '18 at 8:47
|
show 3 more comments
This line doesn't make any sense:
images = Images.objects.filter(post=task)
because task
is a queryset of all the Task instances.
You don't need to get the images at all in the view. Remove that line and the other references, and just do this in the template:
% for obj in task %
<p> obj.title </p>
% for image in obj.images_set.all %
<img src=" image.image.url "</img>
% endfor %
% endfor %
Note also, the Image object has a field called image
, and that's what you need to access the url attribute on.
(For the sake of database efficiency, you might want to change your query slightly in the view:
task = Task.objects.all().order_by('timestamp').prefetch_related('images_set')
otherwise every iteration will cause a separate db call to get the related images. You don't need to do this to make things work, though.)
Cannot find 'images' on Task object, 'images' is an invalid parameter to prefetch_related()
– Mohit Harshan
Oct 25 '18 at 8:38
Are you sure you have posted the correct models? That would work given what you have shown above. Could the model actually be calledImage
rather thanImages
? Does it work without the prefetch_related?
– Daniel Roseman
Oct 25 '18 at 8:43
It is also not pulling any images
– Mohit Harshan
Oct 25 '18 at 8:43
It is not working without prefetch_related . The models are correct
– Mohit Harshan
Oct 25 '18 at 8:44
fixed the issue . It should be % for image in obj.images_set.all %
– Mohit Harshan
Oct 25 '18 at 8:47
|
show 3 more comments
This line doesn't make any sense:
images = Images.objects.filter(post=task)
because task
is a queryset of all the Task instances.
You don't need to get the images at all in the view. Remove that line and the other references, and just do this in the template:
% for obj in task %
<p> obj.title </p>
% for image in obj.images_set.all %
<img src=" image.image.url "</img>
% endfor %
% endfor %
Note also, the Image object has a field called image
, and that's what you need to access the url attribute on.
(For the sake of database efficiency, you might want to change your query slightly in the view:
task = Task.objects.all().order_by('timestamp').prefetch_related('images_set')
otherwise every iteration will cause a separate db call to get the related images. You don't need to do this to make things work, though.)
This line doesn't make any sense:
images = Images.objects.filter(post=task)
because task
is a queryset of all the Task instances.
You don't need to get the images at all in the view. Remove that line and the other references, and just do this in the template:
% for obj in task %
<p> obj.title </p>
% for image in obj.images_set.all %
<img src=" image.image.url "</img>
% endfor %
% endfor %
Note also, the Image object has a field called image
, and that's what you need to access the url attribute on.
(For the sake of database efficiency, you might want to change your query slightly in the view:
task = Task.objects.all().order_by('timestamp').prefetch_related('images_set')
otherwise every iteration will cause a separate db call to get the related images. You don't need to do this to make things work, though.)
edited Oct 25 '18 at 8:48
answered Oct 25 '18 at 8:30
Daniel RosemanDaniel Roseman
447k41580636
447k41580636
Cannot find 'images' on Task object, 'images' is an invalid parameter to prefetch_related()
– Mohit Harshan
Oct 25 '18 at 8:38
Are you sure you have posted the correct models? That would work given what you have shown above. Could the model actually be calledImage
rather thanImages
? Does it work without the prefetch_related?
– Daniel Roseman
Oct 25 '18 at 8:43
It is also not pulling any images
– Mohit Harshan
Oct 25 '18 at 8:43
It is not working without prefetch_related . The models are correct
– Mohit Harshan
Oct 25 '18 at 8:44
fixed the issue . It should be % for image in obj.images_set.all %
– Mohit Harshan
Oct 25 '18 at 8:47
|
show 3 more comments
Cannot find 'images' on Task object, 'images' is an invalid parameter to prefetch_related()
– Mohit Harshan
Oct 25 '18 at 8:38
Are you sure you have posted the correct models? That would work given what you have shown above. Could the model actually be calledImage
rather thanImages
? Does it work without the prefetch_related?
– Daniel Roseman
Oct 25 '18 at 8:43
It is also not pulling any images
– Mohit Harshan
Oct 25 '18 at 8:43
It is not working without prefetch_related . The models are correct
– Mohit Harshan
Oct 25 '18 at 8:44
fixed the issue . It should be % for image in obj.images_set.all %
– Mohit Harshan
Oct 25 '18 at 8:47
Cannot find 'images' on Task object, 'images' is an invalid parameter to prefetch_related()
– Mohit Harshan
Oct 25 '18 at 8:38
Cannot find 'images' on Task object, 'images' is an invalid parameter to prefetch_related()
– Mohit Harshan
Oct 25 '18 at 8:38
Are you sure you have posted the correct models? That would work given what you have shown above. Could the model actually be called
Image
rather than Images
? Does it work without the prefetch_related?– Daniel Roseman
Oct 25 '18 at 8:43
Are you sure you have posted the correct models? That would work given what you have shown above. Could the model actually be called
Image
rather than Images
? Does it work without the prefetch_related?– Daniel Roseman
Oct 25 '18 at 8:43
It is also not pulling any images
– Mohit Harshan
Oct 25 '18 at 8:43
It is also not pulling any images
– Mohit Harshan
Oct 25 '18 at 8:43
It is not working without prefetch_related . The models are correct
– Mohit Harshan
Oct 25 '18 at 8:44
It is not working without prefetch_related . The models are correct
– Mohit Harshan
Oct 25 '18 at 8:44
fixed the issue . It should be % for image in obj.images_set.all %
– Mohit Harshan
Oct 25 '18 at 8:47
fixed the issue . It should be % for image in obj.images_set.all %
– Mohit Harshan
Oct 25 '18 at 8:47
|
show 3 more comments
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52984538%2fnested-for-loops-inside-templates%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Please show the full traceback. And you don't seem to be using formsets at all - where are they?
– Daniel Roseman
Oct 25 '18 at 8:23
Im using formsets as to save the models when submitting the form.This is for displaying.The images are saving correctly! @DanielRoseman
– Mohit Harshan
Oct 25 '18 at 8:26
But you mentioned formsets twice, and I don't understand how they are relevant to your question. You still need to show the traceback.
– Daniel Roseman
Oct 25 '18 at 8:27
sorry for confusing.Edited! @DanielRoseman
– Mohit Harshan
Oct 25 '18 at 8:28