Django:提交表单后从 FormView 重定向到 DetailsView

Django: Redirect from FormView to DetailsView upon submitting the form

相关窗体视图:

class addrecipe(FormView):
    form_class = AddRecipeForm
    model = Recipe
    template_name = 'recipebook/addrecipe.html'
    fields = '__all__'
    extra_context = {
        'recipe_list': Recipe.objects.all()
    }

相关表格:

    class AddRecipeForm(forms.ModelForm):
        name = forms.CharField(max_length="50", label="Recipe Name")
        description = forms.Textarea(attrs={'class': 'desc-text-area'})
        servings = forms.IntegerField()
        tools = forms.ModelMultipleChoiceField(queryset=Tool.objects.all(), widget=forms.CheckboxSelectMultiple, required = True, help_text="Select all relevant tools")

        class Meta:
            model = Recipe
            fields = ("__all__")

URL详情查看页面的模式:

    path('<int:pk>/recipedetails', views.recipedetails.as_view(), name='recipe_details'),

我想让用户提交表单,然后转到他们刚刚输入数据库的条目的详细信息页面。我试过使用 reverse/reverse_lazy 成功了 url 但没有成功。

我还尝试将以下内容添加到我的表单视图中 class:

def get_success_url(self):
    test_recipe_id = self.object.id
    return reverse('recipeBook:recipe_details', pk=test_recipe_id)

同时将我的路径更改为:

re_path(r'(?P<pk>[^/]+)/recipedetails', views.recipedetails.as_view(), name='recipe_details'),

我收到以下值错误:

AttributeError at /recipebook/addrecipe
'addrecipe' object has no attribute 'object'

你的解决方案就差不多了。
您可以使用 get_success_url 方法在模型之后获取配方 ID。这将允许您使用参数重定向。

class addrecipe(FormView):
    form_class = AddRecipeForm
    model = Recipe
    template_name = 'recipebook/addrecipe.html'
    fields = '__all__'
    extra_context = {
        'recipe_list': Recipe.objects.all()
    }
    
    #New method
    def get_success_url(self):
        test_recipe_id = self.object.id #gets id from created object
        return reverse('recipeBook:recipe_details', pk=test_recipe_id)

您的 detail url 没有按预期接收参数,因此需要使用新的正则表达式重新配置它
旧:

path('<int:pk>/recipedetails', views.recipedetails.as_view(), name='recipe_details'),

新:

from django.urls import path, re_path

re_path(r'(?P<pk>[^/]+)/recipedetails', views.recipedetails.as_view(), name='recipe_details),

我需要使用 HttpResponseRedirect 来正确重定向。我的视图最终看起来像这样:

class addrecipe(FormView):
    form_class = AddRecipeForm
    model = Recipe
    template_name = 'recipebook/addrecipe.html'
    fields = '__all__'
    extra_context = {
        'recipe_list': Recipe.objects.all()
    }
    
    def form_valid(self, form):
        test_recipe = form.save(commit=False)
        test_recipe.save()
        test_recipe_id = test_recipe.id
        return HttpResponseRedirect(reverse('recipeBook:recipe_details', kwargs={'pk': test_recipe_id}))

在抓取 ID 之前保存对象似乎是必要的步骤,因为我发现 ID 本身仅在创建对象时创建。

反向 return 不起作用,所以老实说,我欢呼玛丽在前面的 httpresponseredirect,它起作用了。如果我弄清楚原因,我会更新答案..