从DeleteView中的相关模型对象中提取参数以传递给我的get_success_url?

时间:2018-03-26 12:47:24

标签: django-urls django-class-based-views django-generic-views

我有这个模型,与我的用户模式模型有关:

class EntrepreneurshipOffer(models.Model):

    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )
...

此外,我有一个名为EntrepreneurshipOffersByUser的视图,可让我列出我已创建的所有优惠

class EntrepreneurshipOffersByUser(LoginRequiredMixin, UserProfileDataMixin, ListView):
    template_name = 'entrepreneurship/my_entrepreneurship_offer_list.html'

    def get_queryset(self, *args, **kwargs):
        user = self.request.user
        queryset_list = EntrepreneurshipOffer.objects.filter(created_by__username=user.username)
        return queryset_list

    def get_context_data(self, **kwargs):
        context = super(EntrepreneurshipOffersByUser, self).get_context_data(**kwargs)
        user = self.request.user
        entrepreneurship_offers = EntrepreneurshipOffer.objects.filter(created_by__username=user.username)
        context['offers_by_user'] = entrepreneurship_offers
        return context

查看我的EntrepreneurshipOffer个对象的网址是:

# Main URL which call to Entrepreneurship Offer URLs
url(r'^offer/entrepreneurship/', include('entrepreneurship.urls', namespace='offer')),

# List Entrepreneurship Offer's user
    url(r'^by/u/(?P<username>[-\w]+)/$',
        EntrepreneurshipOffersByUser.as_view(),
        name='list'),
    ]

我的问题与删除EntrepreneurshipOffer的目标有关,之后,将工作流重定向到我上面提到的EntrepreneurshipOffer列表对象。

我有EntrepreneurshipOfferDeleteView基于类的视图和get_success_url方法,我在其中调用url列出我的对象,通过命名空间和上面提到的URL名称,添加{{1} URL所需的参数

username

我需要传递class EntrepreneurshipOfferDeleteView(SuccessMessageMixin, UserProfileDataMixin, LoginRequiredMixin, DeleteView): model = EntrepreneurshipOffer #success_url = reverse_lazy("offer:list") success_message = "Oferta de emprendimiento eliminada con éxito" def get_success_url(self): entrepreneurship_offer = self.get_object() #print(entrepreneurship_offer) return reverse_lazy("offer:list", kwargs={'created_by': entrepreneurship_offer.created_by.username}) 参数,但似乎我没有采用合适的方式,因为尽管已将username参数添加到工作流程中,但是{ {1}}我收到此错误:

username

我是基于课堂观点的新手,所以我确定有一个明显的解决办法,但我还没有找到它。

非常感谢任何帮助。感谢。

1 个答案:

答案 0 :(得分:1)

您的网址定义如下:

url(r'^by/u/(?P<username>[-\w]+)/$',
    EntrepreneurshipOffersByUser.as_view(),
    name='list'),
]

因此它需要username参数。但是,你试着把它称为
reverse_lazy("offer:list", kwargs={'created_by': entrepreneurship_offer.created_by.username})即使用created_by。尝试将其更改为

reverse_lazy("offer:list", kwargs={'username': entrepreneurship_offer.created_by.username})它应该有用(或者至少应该抛出不同的错误)。