django - 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 函数中?
解决方案
您需要调用该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)
推荐阅读
- javascript - 使用 jQuery 验证器检查复选框和单选按钮时,不应显示必需的复选框和单选按钮错误
- android-studio - URL 未显示在 android studio logcat 中
- swift - 使用组合布局和多个部分在 UICollectionView 中滚动,而无需重新计算先前单元格的宽度
- android - 如何将回收站视图数据中的 onMove() 更改更新到 sql lite 数据库?
- c# - 用于将调用层次结构重构为异步需要的 C# 工具
- opencv - 来自 OV5647 树莓派相机 v1 的 640 x 480 图像形成
- c - 这会是c中的一个正常工作的自旋锁吗?
- c# - 从 .NET Core 调用 WebAPI 到 .NET Framework
- xamarin - xamarin-bluetooth-le 不扫描设备
- elasticsearch - 在kibana中用@timestamp替换日志文件时间的logstash问题