首页 > 解决方案 > Django CBV post 函数中是否有一种方法可以将信息添加到上下文中

问题描述

我有以下代码

class MusicFileUploadView(TemplateView):
    template_name = "music_file_upload.html"

    def get(self, request, *args, **kwargs):
        return super().get(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        if 'csv-file' in request.FILES.keys():
            csv_file = request.FILES['csv-file']
            upload = FileUpload(csv_file=csv_file)
            if request.user.is_authenticated:
                upload.user_uploaded = request.user
            response = upload.save()
            if response['error']:
                #add error to context
                pass
            else:
                pass
        else:
            pass

        return super().get(request, *args, **kwargs)

在帖子部分我保存上传文件并解析它,以防出现错误,我想在上下文中包含消息,以便我可以在同一页面上显示它。

有没有办法将它包含在 post 函数中?

标签: django

解决方案


您需要调用该get_context_data()方法。

get_context_data()本质上将**kwargs它们作为字典返回,其中任何extra_context来自您的视图类。

因此,当您调用父类时,post()或者get()您需要在 **kwargs 中包含更新后的上下文。

class MusicFileUploadView(TemplateView):
    ...
    def post(self, request, *args, **kwargs):
        # Get the context
        context = self.get_context_data(**kwargs)

        # Modify the context here.

        # Pass the updated context to the parent class
        return super().get(request, *args, **context)

推荐阅读