【问题标题】:Django: reverse_lazy() with a generic viewDjango:具有通用视图的 reverse_lazy()
【发布时间】:2020-03-25 12:08:35
【问题描述】:

我有两个通用视图(CreateViewDetailView)。

在保存表单后的 CreateView 中,我想重定向到 DetailView 以显示我新创建的对象。

但发生错误:Reverse for 'questions.views.DisplayQuestions' not found. 'questions.views.DisplayQuestions' is not a valid view function or pattern name.

如何使用reverse_lazy 调用我的DetailView?

.views:

class DisplayQuestions(ListView):
    model = Question
    context_object_name = "all_questions"
    template_name = "questions/home.html"

    def get_queryset(self):
        return Question.objects.order_by(self.kwargs['display_type'])


@method_decorator(login_required, name='dispatch')
class CreateQuestion(CreateView):
    model = Question
    template_name = 'questions/nouveau.html'
    form_class = QuestionForm

    def get_success_url(self):
        return reverse_lazy(DisplayQuestion) # <-- This doesn't work !!!

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.profil = self.request.user.profil
        self.object = form.save()
        return HttpResponseRedirect(self.get_success_url())

.urls:

urlpatterns = [
    url(r'^nouveau$', views.CreateQuestion.as_view()),
    url(r'(?P<display_type>\w+)', views.DisplayQuestions.as_view()),]

.forms:

class QuestionForm(forms.ModelForm):

    class Meta:
        model = Question
        fields = ('question','categorie',)

【问题讨论】:

  • 究竟应该是什么display_type
  • display_type 应该是单词date

标签: python django django-views


【解决方案1】:

您应该将配置中的每个 url 命名为,

urlpatterns = [
    url(r'^nouveau$', views.CreateQuestion.as_view(), name='create-question'),
    url(r'(?P&ltdisplay_type>\w+)', views.DisplayQuestions.as_view(), name='display-question'),
]

然后访问它,

return reverse_lazy(<b>'display-question', kwargs={'display_type': 'your-display-type-value'}</b>)

参考:Reversing namespaced URLs --(doc)

【讨论】:

  • 谢谢!但是现在我有这个错误Reverse for 'display-questions' with no arguments not found,因为我没有传递参数。我想通过“日期”这个词作为论据。你能帮我吗?
猜你喜欢
  • 2011-01-11
  • 2018-02-21
  • 1970-01-01
  • 2018-07-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 2012-02-23
相关资源
最近更新 更多