繁体   English   中英

Django 模板过滤已呈现的查询集

[英]Django Template filter the query set already rendered

我有 model

class TransHeader(models.Model):
    th_type = models.CharField(max_length=200)
    th_code = models.CharField(max_length=200)
    th_status=models.CharField(max_length=1,default=0)

我的观点:

class SalTransactions(TemplateView):
    template_name = "wstore/sales_transactions.html"
    def get_context_data(self, **kwargs):
        context = {}
        if  kwargs['post']=='UNPOSTED':
            context['transactions'] =          
               TransHeader.objects.filter(th_type=kwargs['transtype'])
               .filter(th_status='0')
        else:
      
            context['transactions'] = 
            TransHeader.objects.filter(th_type=kwargs['transtype'])
        return context

我的 url 线:

 path('saltransactions/<str:transtype>/<str:post>',views.SalTransactions.as_view(), name='saltransactions'),

我通过菜单的链接工作正常,显示给定 trans 类型的所有记录:

  <a class="nav-link" href="{% url 'saltransactions' transtype='INV' post='ALL' %}">Sales</a>

<a class="nav-link" href="{% url 'saltransactions' transtype='ADJ' post='ALL' %}">Stock Adjustment</a>

但是当我过滤以显示只有 th_status='0' 的 rocords 时,我在模板中使用以下链接:

 <a href="{% url 'saltransactions'  transtype=?????"  post='UNPOSTED' %}" >Unposted</a>

我的问题是如何通过 INV 或 ADJ 从查询集中进行转换。 如果我分配 transtype='INV' 它正在过滤两种类型的 INV 查询集。

这样我就可以对所有类型的交易(INV/ADJ)使用一个视图、一个模板

谢谢你的帮助

问题是,在您的get_context_data中,您正在检查 POST 请求。 但是,该链接不是 POST 请求,而是一个简单的 GET 请求。 您需要一个实际发布数据的表单,如下所示:

# in your template
<form method="post" action="/my/url/to/post/to">
   <input type="hidden" name="transtype" value="MY_VALUE" />
   <input type="submit" value="Filter" />
</form>

此外,在视图中,最好检查self.request.method ,如果它是 POST 或 GET 请求。 在这两种情况下,您都可以通过self.request.POST访问数据,它会返回您通过表单发布的数据。 对于 GET 请求,您传递给 url 的任何内容,因此myurl.com/?transtype=something将可以通过self.request.GET访问。 如果您使用 kwargs,它可能无法按预期工作,因为在kwargs中可能还有一些其他称为post的东西。

You can read up on it in here: https://docs.djangoproject.com/en/3.1/ref/request-response/#django.http.HttpRequest.method https://docs.djangoproject.com/en/3.1 /ref/request-response/#django.http.HttpRequest.POST

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM