基于Django类的视图和查询

时间:2017-03-19 21:36:01

标签: python django django-templates django-views

我正在尝试过滤单个对象,更具体地说,是今天的条目。然后,我想获取该查询并在模板中显示结果。无论我做什么,我似乎无法让过滤器在模板中显示任何内容。我不确定是否需要在视图,模型或两者中编写查询。我对Django查询的熟悉程度很轻松。关于这个主题的一个很好的资源也非常有用。

我是Django的新手,所以你能提供的任何帮助都会非常感激。

models.py

class Entry(models.Model):
    date = models.DateField(blank=True, null=True,)
    euros = models.CharField(max_length=500, blank=True, null=True)
    comments = models.CharField(max_length=900, blank=True, null=True)
    euros_sum = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)
    xrate = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)
    dollars_sum = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)
    daily_savings_dollars = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)

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

views.py:

    class IndexView(generic.ListView):
        template_name = 'argent/index.html'
        context_object_name = 'object_list'
        queryset = Entry.objects.all()
        filter = Entry.objects.filter(date=today_date)
        print(filter)


    class DetailView(generic.DetailView):
        model = Entry
        template_name = 'argent/detail.html'


    class EntryCreate(CreateView):
        form_class = EntryForm
        template_name = 'argent/entry_form.html'

        def form_valid(self, form):
            return super(EntryCreate, self).form_valid(form)


    class EntryUpdate(UpdateView):
        model = Entry
        form_class = EntryForm
        template_name = 'argent/entry_form.html'

        def form_valid(self, form):
            return super(EntryUpdate, self).form_valid(form)
  

注1:当我打印“filter =”时,我会在控制台中返回正确的对象。

     

注意2:我在我的模板中使用了我的“queryset =”并且它可以工作   完全没问题。

模板(index.html的):

<div class="container" style="font-family: 'Dosis', serif;">
    <div class="jumbotron" style="background: #ebebeb">

        {% for Entry in filter %}

        <h1>Today's Spending</h1>
        <div class="container container-fluid" style="margin-left: 30px; margin-right: 30px; font-family: 'Dosis', serif; color: white;">
        <div class="container container-fluid">
            <table class="table">
                <thead>
                    <tr>
                        <th colspan="2" style="font-size: large; color: #337ab7; font-weight: bold">{{ first.date }}</th>
                    </tr>
                </thead>
                <tbody>
                <tr>
                    <td align="left" style="color: #337ab7; font-weight: bold">Receipts:</td>
                    <td style="color: #FF6F18;"> {{ first.euros }} </td>
                </tr>
                <tr>
                    <td align="left" style="color: #337ab7; font-weight: bold">Total Euros Spent:</td>
                    <td style="color: #FF6F18;">€{{first.euros_sum}}</td>
                </tr>
                <tr>
                    <td align="left" style="color: #337ab7; font-weight: bold">Total Dollars Spent:</td>
                    <td style="color: #FF6F18;">${{first.dollars_sum}}</td>
                </tr>
                <tr>
                    <td align="left" style="color: #337ab7; font-weight: bold">Exchange Rate:</td>
                    <td style="color: #FF6F18;">{{ first.xrate }}</td>
                </tr>
                <tr>
                    <td align="left" style="color: #337ab7; font-weight: bold">Daily Savings:</td>

                    <td style="color: #FF6F18;">
                        {% if last.daily_savings_dollars > 0 %}
                        <div class="NegativeSavings" style="font-weight: bold">-
                        {% else %}
                        <div class="PositiveSavings" style="font-weight: bold">+
                        ${{ first.daily_savings_dollars }}
                        </div>
                    </td>
                </tr>
                </tbody>
            </table>
            </div>
          </div>
        {% endfor %}
<div class="container container-fluid" style="font-family:'Dosis', serif">

    <!-- Entry List -->
    <div class="row" style="margin-left: 20px; margin-right: 20px">
        <div>
            &nbsp
        </div>
        {% if object_list %}
            {% for Entry in object_list %}
                <div class="col-sm-4 col-lg-3">
                    <div class="thumbnail" style="background: #ebebeb"; >
                        <a href="{% url 'argent:detail' Entry.id %}">
                            <h3 align="center" style="font-weight: bold">{{ Entry.date }}</h3>
                        </a>
                        <div class="caption">
                            <h4 align="center" style="color: #FF6F18">€{{ Entry.euros_sum }}
                            <!-- View Details -->
                            <a href="{% url 'argent:detail' Entry.id %}"><button type="button" class="btn btn-link btn-lg">
                            <span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span>
                            </button></a>

                            <!-- Update -->
                            <a href="{% url 'argent:entry-update' Entry.id %}"><button type="button" class="btn btn-link btn-lg" style="padding: 0%">
                            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
                            </button></a></h4>
                        </div>
                    </div>
                </div>
            {% endfor %}
        {% endif %}
    </div>
</div>

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

您不应该在模块级别进行任何数据库交互。您应该覆盖get_queryset(对于将object_list传递给模板的内容)和get_context_data,如果您想要模板上下文中的其他内容,例如过滤的查询集:

from django.utils import timezone

class IndexView(generic.ListView):
    template_name = 'argent/index.html'
    context_object_name = 'object_list'

    def get_queryset(self):
        return Entry.objects.all()

    def get_context_data(self, **kwargs):
        ctx = super(IndexView, self).get_context_data(**kwargs)
        ctx['filter'] = Entry.objects.filter(date=timezone.datetime.today())
        return ctx

django文档in general及其ListView部分是一个很好的起点。 django tutorial也值得完成。

答案 1 :(得分:1)

修改视图以将其中一个查询集作为上下文传递。

   class IndexView(generic.ListView):
       template_name = 'argent/index.html'
       context_object_name = 'object_list'
      #queryset = Entry.objects.all() use the get_queryset method to get this
      #filter = Entry.objects.filter(date=today_date)  add this using the get_context_data method

       def get_context_data(self, **kwargs):
           context = super(IndexView, self).get_context_data(**kwargs)
           context.update({
           'filter': Entry.objects.filter(date=today_date),
           })
           return context

       def get_queryset(self):
           return  Entry.objects.all()