如何在Django

时间:2018-02-20 13:23:49

标签: django listview

我有一个类jourListView(ListView)。我想在我的html模板中输入日期,然后检索日期以制作过滤器。 我的类jourListView(ListView)引用了两个链接表。 我陷入了困境。如何让我的代码正常运行?

这是我的模型,视图和模板。

class jour(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE, related_name='jour')
    date = models.DateField(blank=True, null=True)
    commentaire = models.CharField(max_length=500, blank=True, null=True)
    class Meta:
        managed = False
        db_table = 'jour'
        unique_together = (('id'),)
        verbose_name = 'JOUR'
        verbose_name_plural = 'JOUR'

    id = models.AutoField(primary_key=True)

    def get_absolute_url(self):
        return reverse("jour_detail",kwargs={'pk':self.pk})

    def __str__(self):
        return str(self.date) ##


class activite(models.Model):
    jour = models.ForeignKey('blog.jour',on_delete=models.CASCADE, related_name='jour' )
    name= models.CharField(max_length=500, blank=True, null=True)
    class Meta:
        managed = False
        db_table = 'activite'
        unique_together = (('id'),)
        verbose_name = 'ACTIVITÉ'
        verbose_name_plural = 'ACTIVITÉ'

    id = models.AutoField(primary_key=True)

    def __str__(self):
        return self.type

    def get_absolute_url(self):
        return reverse("jour_list")

我的观点:

class jourListView(ListView):
    model = jour
    def get_context_data(self, **kwargs):
        if request.method == 'POST':
            date_insert = request.POST.get('date_ref')
            context = super(jourListView, self).get_context_data(**kwargs)
            context['count'] = self.get_queryset().count()
            return context

    def get_queryset(self):
        return jour.objects.filter(date__lte=timezone.now()).filter(user=self.request.user).filter(date__in=date_insert)

我的html模板:

{% if user.is_authenticated %}

  <div class="container text-center">
      <form class="form-signin" id="login_form" method="post" action="/blog/list/">
        {% csrf_token %}

        <br>
        <input type="date" name="date_ref" class="form-control" placeholder="SAISIE DATE " value="" required autofocus>
        <br>
        <button class="btn btn-lg btn-primary btn-block" type="submit">OK</button>
      </form>
  </div>

    <div class="centerstage">

        {% for jour in jour_list %}
            <div class="post">
              <p class='postcontent' ><strong>Date:</strong> {{ jour.date }}</p>
              <p class='postcontent' ><strong>Commentaire:</strong> {{ jour.commentaire }}</p>
              <a class="btn btn-primary" href="{% url 'jour_edit' pk=jour.pk %}"><span class="glyphicon glyphicon-pencil"></span></a>
              <h1><a href="{% url 'jour_detail' pk=jour.pk %}">Détails activités</a></h1>
            </div>
        -----------------
        {% endfor %}

    </div>

{% endif %}

我改变了我的观点,但它不起作用。

class jourListView(ListView):
model = jour
template_name = "blog/list.html"
def get_context_data(self, **kwargs):
    if request.method == 'POST':
        date_insert = request.POST.get('date_ref')
        context = super(jourListView, self).get_context_data(**kwargs)
        context['count'] = self.get_queryset().count()
        return context

def get_queryset(self):
    queryset = jour.objects.filter(date__lte=timezone.now()).filter(user=self.request.user)
    date_insert = request.POST.get('date_ref')
    if date_insert:
        queryset = queryset.filter(date=date_insert)
    return queryset

另外我还有另一个错误: NameError在/ blog / list / 名称'request'未定义

请求方法: GET

请求网址: http://127.0.0.1:8000/blog/list/

Django版本: 2.0.2

异常类型: NameError

异常值: 名称'request'未定义

2 个答案:

答案 0 :(得分:0)

在使用date_insert方法之前,您需要在get_queryset方法中定义class jourListView(ListView): model = jour def get_context_data(self, **kwargs): if self.request.method == 'POST': date_insert = self.request.POST.get('date_ref') context = super(jourListView, self).get_context_data(**kwargs) context['count'] = self.get_queryset().count() return context def get_queryset(self): queryset = jour.objects.filter(date__lte=timezone.now()).filter(user=self.request.user) date_insert = self.request.POST.get('date_ref') if date_insert: queryset = queryset.filter(date=date_insert) return queryset 。例如:

Jour

一旦有效,您可能需要考虑进一步的改进

  • 将模型重命名为get_context_data以匹配Django样式
  • 确保在LoginRequiredMixin中为GET请求和POST请求返回上下文。
  • 使用date_insert确保只有已登录的用户才能访问该视图
  • 添加检查以处理{{1}}不是有效日期字符串的情况。

答案 1 :(得分:0)

我找到了解决问题的方法。 结果如下:

我受到此链接中的示例的启发: Django: Search form in Class Based ListView

我的观点:

class jourListView(ListView):
    model = jour
    template_name = "blog/list.html"
    def get_context_data(self, **kwargs):
        context = super(jourListView, self).get_context_data(**kwargs)
        # FILTER BY CURRENT MONTH, USER
        filter_ = jour.objects.filter(date__lte=timezone.now()).filter(user_id=self.request.user).order_by('-date')
        if self.request.GET.get('date_ref'):
            date_insert  = self.request.GET.get('date_ref')
            filter_ = filter_.filter(date=date_insert) 
        context['jourListView'] = filter_
        return context

我的模板(blog / list.html):

{% extends 'blog/base.html' %}
{% block content %}
    {% if user.is_authenticated %}
            <form class="navbar-form navbar-right"  action="." method="get">
                {{ form.as_p }}
                <input id="date_ref" name="date_ref" type="date" placeholder="Localizar..." class="form-control">
                <button type="submit" class="btn btn-success form-control"><span class="glyphicon glyphicon-search"></span></button>
            </form>

            {% if jourListView %}
                {% for select_value in jourListView %}
                    <div class="post">
                      <p class='postcontent' ><strong>Date:</strong> {{ select_value.date}}</p>
                      <p class='postcontent' ><strong>User ID:</strong> {{ select_value.user_id}}</p>
                      <p class='postcontent' ><strong>Status:</strong> {{ select_value.status}}</p>
                    </div>
                -----------------
                {% endfor %}
            {% endif %}
    {% endif %}
{% endblock %}