如果对象存在,Django过滤并显示在模板中

Posted

技术标签:

【中文标题】如果对象存在,Django过滤并显示在模板中【英文标题】:Django filter and display in template if object exists 【发布时间】:2019-04-05 22:47:22 【问题描述】:

models.py:

class Level(models.Model):
    number = models.IntegerField()
    badge = models.ImageField()
    locked_badge = models.ImageField()
    timestamp=
    models.DateTimeField(auto_now_add=True,auto_now=False,blank=True, 
    null=True)
    unlock = models.CharField(max_length=10,default="A")

    def __str__(self):
        return str(self.number)
    def get_absolute_url(self):
        return reverse('student:level-detail', kwargs='pk': self.pk)

class ToDo(models.Model):
    level = models.ForeignKey(Level, on_delete=models.CASCADE)
    name = models.CharField(max_length=150)
    description = models.TextField()
    timestamp = 
    models.DateTimeField(auto_now_add=True,auto_now=False,blank=True, 
    null=True)

    def __str__(self):
        return self.name


class PostManager(models.Manager):
    def active(self, *args, **kwargs):
        #Post.objects.all() = super(PostManager, self).all()
        return super(PostManager, 
        self).filter(draft=False).filter(publish__lte=timezone.now())



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

我的意见.py:

@login_required(login_url='/account/login/')
def StudentLevelDetailView(request,pk=None):

    if not request.user.is_client:
        return HttpResponse("You are in trainer account")

    else:
        Client=ClientProfile.objects.get(user=request.user)
        subscription=Client.subscription
        instance = get_object_or_404(Level, pk=pk)

        todos=ToDo.objects.filter(level=instance)
        tasks=Task.objects.filter(todo=todos,level=instance)


        notifications =  
        Notification.objects.exclude(sender=request.user)
        .filter(receiver=request.user).order_by('-timestamp')
        acceptnotify = Addnotify.objects
       .filter(receiver=request.user).order_by('-timestamp')
       follownotify = FollowNotify.objects
       .filter(receiver=request.user).order_by('-timestamp')
       hubnotifications = HubNotify.objects
       .filter(receiver=request.user).order_by('-timestamp')
       newnotifications = int(
       Notification.objects.exclude(sender=request.user)
       .filter(receiver=request.user, viewed=False).count() +
        FollowNotify.objects.exclude(sender=request.user)
       .filter(receiver=request.user, viewed=False).count() +
        HubNotify.objects.exclude(sender=request.user)
       .filter(receiver=request.user, viewed=False).count() +
         Addnotify.objects.exclude(sender=request.user)
       .filter(receiver=request.user, viewed=False).count())

        global is_paid_member
        global is_paid_fellow
        context = 
         'paidmember':is_paid_member,
         'paidfellow': is_paid_fellow,
         'task': instance,
         'tasks':tasks,
         'notifications': notifications,
         'newnotify': newnotifications,
         'completed':False,
         'subscription': subscription,
         'hubnotify': hubnotifications,
         'acceptnotify': acceptnotify,
         'follownotify': follownotify,
     

        return render(request,'task_list.html',context)

模板:

 % for obj in task.todo_set.all %
    <div class="card">
    <div class="card-header" id="headingOne">
        <h5 class="mb-0">
        <button style="width: 100%;" class="btn" data- 
toggle="collapse" data-target="# obj.id " aria-expanded="true">
    #Only display based on condition        
<span class="mytaskbutton"><i class="fas fa-check"></i> 
 </span></i> &nbsp;
  obj.name 
        </button>
        </h5>
    </div>

    <div id=" obj.id " class="collapse" aria- 
  labelledby="headingOne" data-parent="#accordion">
        <div class="card-body">
             obj.description 
        <div>
        <a data-click="swal-taskcompleted" href="% url 'student:task- 
  form' task.id obj.id %" style="width: 100%;" type="button" 
  class="btn btn-primary">Proceed</a>
        </div>
        </div>
    </div>
    </div>
  % endfor %

填写表格时保存任务:

@login_required(login_url='/account/login/')
 def TaskCreateView(request,pk,todo_id):
     if not request.user.is_authenticated:
        return redirect('accounts:index')
     elif User.objects.filter(pk=request.user.pk, 
        mentor__isnull=True).exists():
        instance = get_object_or_404(Level, pk=pk)
        sweetify.error(request, 'You have not added a trainer yet')
        print("TRAINER ILADA")


        return HttpResponseRedirect(instance.get_absolute_url())
     else:
       instance = get_object_or_404(Level, pk=pk)
       qs = instance.todo_set.get(id=todo_id)
       #user = Task.objects.filter(student=request.user)
       todo = Task.objects.filter(todo=qs, student=request.user)

       print("TODO COUNT",todo.count())

     if todo.exists():
        print("TODO COUNT ALRAESY EXISTA", todo.count())
        messages.error(request, 'You already completed this task')
        return redirect('student:level-detail',pk=instance.id)

     form = StudentTaskForm(request.POST or None, request.FILES or None)

    if form.is_valid():
        form.instance.user = User.objects.get(id=request.user.id)

        obj = form.save(commit=False)
        obj.student = request.user
        obj.todo = qs
        obj.level = instance
        obj.save()



    ImageFormSet = modelformset_factory(Images,
                                        form=ImageForm,min_num=0,
                                 max_num=3,  
    validate_min=True,extra=3)

    if request.method == 'POST':
        formset = ImageFormSet(request.POST, request.FILES,
                           queryset=Images.objects.none())
    if formset.is_valid():
        for form in formset.cleaned_data:
            try:
                image = form['image']

                Images.objects.create(post=todo[0],image=image)
            except KeyError:
                pass
         return redirect('student:dashboard')
     else:
        formset = ImageFormSet(queryset=Images.objects.none())

        notifications = 
Notification.objects.exclude(sender=request.user)
       .filter(receiver=request.user)
       newnotifications = int(
       Notification.objects.exclude(sender=request.user)
       .filter(receiver=request.user, viewed=False).count() +
       FollowNotify.objects.exclude(sender=request.user)
    .filter(receiver=request.user, viewed=False).count() +
    HubNotify.objects.exclude(sender=request.user)
   .filter(receiver=request.user, viewed=False).count() +
    Addnotify.objects.exclude(sender=request.user)
   .filter(receiver=request.user, viewed=False).count())

   hubnotifications=HubNotify.objects
   .filter(receiver=request.user).order_by('-timestamp')
    acceptnotify = Addnotify.objects
  .filter(receiver=request.user).order_by('-timestamp')
   follownotify = FollowNotify.objects
  .filter(receiver=request.user).order_by('-timestamp')
  counts=int(todo.count())

 context=
    'form': form,
    "qs": qs,
    'todo':todo,
    'formset': formset,
    'notifications': notifications,
    'hubnotify': hubnotifications,
    'newnotify': newnotifications,
    'acceptnotify': acceptnotify,
    'follownotify': follownotify,




return render(request,'task_form.html',context)

StudentTaskForm 是一个模型表单。有模型作为任务

我有 3 个模型。待办事项、关卡和任务。每个级别包含许多“待办事项”。任务基本上都是完成的todos。所以如果一个待办事项完成了,它就会被保存为一个任务。如果“待办事项”已经完成,我希望显示“待办事项”列表中的复选图标,也就是说,如果这个“待办事项”被保存为任务。仅当此待办事项完成时,才应显示具有“fas fa-check”类的图标。 “待办事项”显示为列表。在模板中,关卡作为“任务”传递...所以关卡中的所有“待办事项”都由 task.todo_set.all 拉取...我想要任务中的“待办事项”,基本上是所有完成的待办事项都有检查

【问题讨论】:

哦,那么您的视图是什么样的?看来这一切都可以在您的视野中处理。 我已经在我的问题中更新了它。 @CarlBrubaker 所以你想检查% for obj in task.todo_set.all %中的每个obj 是的......只有一件事......任务实际上是这里的水平......所有任务,我作为任务传递@CarlBrubaker 对不起..这不是我想要的。我不想检查每个对象...对于任务模型,Todo 有一个外键...我正在显示关卡的 todoset。 ....我只想检查保存在任务中的待办事项,这意味着待办事项已完成@CarlBrubaker 【参考方案1】:
  tasks = Task.objects.filter(student=request.user,level=instance).only("todo")
  list=[]
  for task in tasks:
     list.append(task.todo)

这对我有用。我将过滤后的tasks 中的所有todos 添加到list,然后将此列表传递给template。然后我只需要比较

 % if obj in list %
  #display check
 % endif %

【讨论】:

【参考方案2】:

因此,您希望将level 中的所有todos 显示为student,并在已完成的旁边显示checks

查看

# find all todos for level.
todos=ToDo.objects.filter(level=instance)
# lists to hold todos.
complete = []
incomplete = []
# Separate complete and incomplete todos.
for todo in todos:
    # Check if task exists to signify complete.
    if Task.objects.filter(student=student, todo=todo).exists():
        complete.append(todo)
    else:
        # If no task, add to incomplete.
        incomplete.append(todo)

# Send both lists to template.
'complete': complete, 'incomplete': incomplete

模板

% for c in complete %
  <!-- If complete make it checked. -->
  <div><input type="checkbox" checked>Todo Detail</div>
% endfor %
% for i in incomplete %
  <!-- If incomplete leave it unchecked. -->
  <div><input type="checkbox">Todo Detail</div>
% endfor %

至于受保护的检查checkboxes,请查看此link 以了解适合您的方法。

希望这能让你走上正轨。

【讨论】:

任务模型实际上只是使用模型形式。因此,只有当用户填写表单时,才会将对象保存为任务,这相当于完​​成待办事项。那么这个布尔字段是必要的吗? 如何从过滤后的 Task 对象中只获取 todo 字段...通过这个我可以比较 % if obj in filteredtodo % 您确定可以在模板内进行过滤吗? 糟糕。不,检查一下。 template filter 好的,最后一次尝试。我将删除我的大部分 cmets,因为它们现在看起来无关紧要。

以上是关于如果对象存在,Django过滤并显示在模板中的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Django 模板中显示我过滤对象的其他条目

如何过滤和统计 DJANGO 模板中的对象?

django视图中的elif条件

在对象属性的“js”脚本中应用 django 的模板过滤器

在 django 模板中过滤外键对象

使用 Django 模板过滤器限制字符数