Django 如何通过 FormView 重命名上下文对象?

标签 django django-class-based-views

我有一个使用 FormView 的类 View 。我需要更改表单的名称,即在我的旧函数 View 中以前是这样的:

 upload_form = ContactUploadForm(request.user)
 context = {'upload': upload_form,}
在我的新 View 中,我假设我可以使用 get_context_data 方法重命名,但不确定如何重命名。
我如何将此表单重命名为 上传 而不是 表单 因为我的模板使用 {{ upload }} 而不是 {{ form }} ?谢谢。
当前类 View :
class ImportFromFile(FormView):

    template_name = 'contacts/import_file.html'
    form_class = ContactUploadForm

    def get_context_data(self, **kwargs):
        """
        Get the context for this view.
        """
        # Call the base implementation first to get a context.
        context = super(ImportFromFile, self).get_context_data(**kwargs)

        return context

最佳答案

试试这个:

class ImportFromFile(FormView):

    template_name = 'contacts/import_file.html'
    form_class = ContactUploadForm

    def get_context_data(self, **kwargs):
        """
        Get the context for this view.
        """
        kwargs['upload'] = kwargs.pop('form')
        return super(ImportFromFile, self).get_context_data(**kwargs)

关于Django 如何通过 FormView 重命名上下文对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17272614/

相关文章:

python - 在 alpine docker 容器中安装 psycopg2

django - 仅在 IE9 上使用 django 表单提交的 HTTP 403

列 "owner_id"中/new null 值处的 Django IntegrityError 违反了非空约束

python - Django CreateView 给出错误 "needs to have a value for field ".. ."before this many-to-many relationship can be used."

Python zipfile 未交付给用户

python - Django 帖子未显示在主页上,但显示在类别列表中

javascript - 将 bool 字符串查询传递给 Django

用于创建和更新的基于 Django 类的 View

Django 表单 : most DRY way to organize create/update forms for inherited models

python - 在 FormView form_valid 方法中更新上下文数据?