嵌套在模板内的for循环中 [英] nested for loops inside templates

查看:47
本文介绍了嵌套在模板内的for循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

models.py

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

我有两个模型Task和Images.我为任务保存了多个图像.我想使用分页显示任务列表以及每个任务中的图像.

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)

如何使用for循环使图像正确显示在模板中

How do i get the images to display correctly inside the template using for loops

我正在尝试

  {% for obj in task %}
  <p>{{ obj.title }}

  {% for image in images %}
   <img src="{{ image.url }}"</img>
   {% endfor %}

  {% endfor %}

出现错误:必须使用切片将精确查找的QuerySet值限制为一个结果.

Im getting the error: The QuerySet value for an exact lookup must be limited to one result using slicing.

推荐答案

此行没有任何意义:

images = Images.objects.filter(post=task)

因为 task 是所有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 %}

还请注意,Image对象具有一个名为 image 的字段,这就是您需要访问其url属性的地方.

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')

否则,每次迭代将导致单独的db调用以获取相关图像.不过,您无需执行此操作即可使它正常运行.)

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.)

这篇关于嵌套在模板内的for循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆