如何在RedirectView Django中重定向回同一页面

时间:2018-07-20 23:19:16

标签: django python-3.x django-templates django-views

我具有下面的视图,我试图将用户重定向到我的 views.py

class TastingPickedToggle(LoginRequiredMixin, RedirectView):
    def get_redirect_url(self, *args, **kwargs):
        pk = self.kwargs.get('pk')
        obj = get_object_or_404(OrderItem, pk=pk)
        user = obj.order.buyer

        if user in obj.picked.all():
            obj.picked.remove(user)
        else:
            obj.picked.add(user)
        return redirect('order:tasting_sold_orders')

但是出现页面未找到(404)错误。

下面是我的 models.py

class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items_in_this_order')
picked = models.ManyToManyField(User, blank=True, related_name='item_picked')

   def get_absolute_url(self):
        return reverse('order:tasting_sold_detail', kwargs={'username': self.order.buyer.username,
                                                            'pk': self.pk})

    def get_picked_url(self):
        return reverse('order:pick', kwargs={'username': self.order.buyer.username,
                                             'pk': self.pk})

下面是我的 urls.py

urlpatterns = [


    url(r'^tasting_sold_orders/$', views.TastingsSoldOrders.as_view(), name='tasting_sold_orders'),

    url(r'^(?P<username>[-\w]+)/(?P<pk>\d+)/pick/$', views.TastingPickedToggle.as_view(), name='pick'),

下面是我的 templates.py

  {% if order.order.buyer in order.picked.all %}
    <a href="{{ order.get_picked_url }}"><button class="btn btn-success">Picked</button></a>
   {% else %}
     <a href="{{ order.get_picked_url }}"><button class="btn btn-default">Not picked</button></a>
  {% endif %}

逻辑有效。如果我返回并刷新按钮,则颜色已更改。如何获得返回重定向以工作

1 个答案:

答案 0 :(得分:1)

我刚刚将返回重定向更改为返回反向,并且有效

class TastingPickedToggle(LoginRequiredMixin, RedirectView):
    def get_redirect_url(self, *args, **kwargs):
        pk = self.kwargs.get('pk')
        obj = get_object_or_404(OrderItem, pk=pk)
        user = obj.order.buyer

        if user in obj.picked.all():
            obj.picked.remove(user)
        else:
            obj.picked.add(user)
        return reverse('order:tasting_sold_orders') #just changed this to reverse and it worked