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

时间:2018-11-01 16:58:16

标签: python django

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

我的views.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是模型表单。具有模型作为Task

我有3个模型。待办事项,级别和任务。每个级别包含许多“待办事项”。任务基本完成了。因此,如果待办事项完成,则将其另存为任务。我想如果“ todo”已经完成,即如果“ todo”已保存为任务,则显示“ todo”列表中的复选图标。仅在完成此待办事项后,才应显示“ fas fa-check”类的图标。 “待办事项”显示为列表。在模板中,级别作为“任务”传递...因此,该级别中的所有“待办事项”都由task.todo_set.all ...拉出。所有完成的待办事项都要检查

2 个答案:

答案 0 :(得分:0)

因此,您希望将todoslevel中的所有studentchecks一起显示在已完成的内容旁边。

视图

# 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来查看适合您的内容。

希望这能使您走上正确的轨道。

答案 1 :(得分:0)

  tasks = Task.objects.filter(student=request.user,level=instance).only("todo")
  list=[]
  for task in tasks:
     list.append(task.todo)

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

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