【问题标题】:Click button in table and redirect to same page单击表中的按钮并重定向到同一页面
【发布时间】:2020-08-31 14:10:58
【问题描述】:

我有一个看法:

class ProductList(SingleTableView):
    model = Product
    template_name = "app/product_list.html"
    table_class = ProductTable

每一行都有一个应该执行function()的按钮:

class ButtonColumn(tables2.Column):
    empty_values = list() 
    def render(self, value, record): 
        return mark_safe(f"""<a href="/link/{record.id}/"><button class="btn btn-info">link</button></a>""")

这个ButtonColumn 提供了一个按钮,一旦被点击:

    path("link/<int:pk>", views.LinkView.as_view(), name="link"),

以及对应的视图:

class LinkView(TemplateView):
    model = Product
    template_name = "app/product_list.html"

    def get_success_url(self):
        return reverse_lazy('product-list')

    def get_context_data(self, **kwargs):
        context = super(LinkView, self).get_context_data(**kwargs)
        function[kwargs] # <------------------
        context["table"] = Product.objects.all()
        return(context)

我的问题在于 Linkview - 我希望它使用一些 URL 传输参数执行 function 并返回到前一页 (app/product_list.html)。我怎样才能做到这一点?

【问题讨论】:

    标签: django django-views django-tables2


    【解决方案1】:

    像这样修改ButtonColumn

    class ButtonColumn(tables2.Column):
        empty_values = list() 
        def render(self, value, record): 
            return mark_safe(f"""<a href="/link/{record.id}/?price=10"><button class="btn btn-info">link</button></a>""")
    # There is no need to mention these query parameter in path. 
    

    路径将保持不变。 无需更改任何内容

        path("link/<int:pk>", views.LinkView.as_view(), name="link"),
    

    ListView 中,您将使用self.request.GET.get("param1", ""),其中param1 是URL 传输参数,"" 是默认值。

        def get_context_data(self, **kwargs):
            context = super(LinkView, self).get_context_data(**kwargs)
            param1 = self.request.GET.get("param1", "")
            # OR
            function(self.request.GET) # extract required params in the function
            function[kwargs] # <------------------
            context["table"] = Product.objects.all()
            return(context)
    

    注意:Get是字典

    要重定向,

    from django.shortcuts import redirects
    
    # In your LinkView override get method
    class LinkView(TemplateView):
        def get(self, request, *args, **kwargs)
            return redirect('some/url')
    

    【讨论】:

    • 我用这个 urls.py 条目尝试了你的建议:path(r"link/(&lt;int:pk&gt;/(?P&lt;price&gt;[0-9]+)$", views.Linkiew.as_view(), name="link") 导致404: Request URL: http://127.0.0.1:8000/link/30/?price=10。另外,您的建议如何将我重定向到我以前的视图 (app/product_list.html)?
    • 路径中不需要添加查询参数price。只需在 url 中传递它们并访问视图中的参数。至于重定向,从代码中,我知道用户已经在LinkView 上,不需要在任何地方重定向用户。
    • 用户在ProductListView 上单击按钮,该按钮通过LinkView 执行功能,但他最终应该回到ProductListView
    • 要重定向,你需要覆盖LinkViewget方法。
    猜你喜欢
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 2021-09-07
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多