我有一个使用FormView的类视图。我需要更改表单的名称,即,这就是我以前的函数视图中的样子:
upload_form = ContactUploadForm(request.user)
context = {'upload': upload_form,}
使用新视图,我假设可以使用get_context_data方法重命名,但不确定如何。
How can I rename this form to **upload** not **form** as my templates uses `{{ upload }}` not `{{ form }}`? Thanks.
当前班级视图:
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 2.0+提供了更改上下文对象名称的支持。请参阅:Built-in class-based generic views
建立“友好的”模板上下文
[您可能已经注意到我们的示例发布者列表模板将所有发布者存储在名为object_list的变量中。尽管这很好用,但对模板作者并不是那么“友好”:他们必须“只是知道”他们在这里与发布者打交道。
好吧,如果您要处理模型对象,已经为您完成了。当您处理对象或查询集时,Django可以使用模型类名称的小写形式填充上下文。除了默认的object_list条目之外,还提供了该条目,但包含的数据完全相同,即Publisher_list。
如果仍然不太合适,则可以手动设置上下文变量的名称。通用视图上的
context_object_name
属性指定要使用的上下文变量:class PublisherList(ListView): model = Publisher context_object_name = 'choose the name you want here'