【发布时间】:2017-12-19 19:52:40
【问题描述】:
我有一个用于注册/登录的导航栏项目。因为,它将在不同的页面中,我正在考虑在“base.html”中为每个页面调用此表单“一次”。
我发现了“上下文处理器”(Django - How to make a variable available to all templates?),但是,正如我所见,它只将一个变量传递给所有模板,在一个函数中(不使用一个 View 类,带有 get 和 post 方法)。
为此,它在文件中使用了类似这样的函数:
view.py:
def categories_processor(request):
categories = Category.objects.all()
return {'categories': categories}
但是,我在 views.py 中使用了类视图,并且通常我会传递“请求”、“要呈现的 URL”、“上下文”。像这样:
view.py:
class RegistroClienteView(View):
def get(self, request):
ls_tipos_de_documento = TipoDocumento.objects.values_list('id', 'nombre_corto')
form = ClienteCreationForm()
context = {'form': form, 'ls_tipos_de_documento': ls_tipos_de_documento}
return render(request, 'app_cliente/frontend/ingreso.html', context)
def post(self, request):
ls_tipos_de_documento = TipoDocumento.objects.values_list('id', 'nombre_corto')
form = ClienteCreationForm(request.POST)
if form.is_valid():
form.save()
context = {'form': form}
return render(request, 'app_cliente/frontend/ingreso.html', context)
context = {'form': form, 'ls_tipos_de_documento': ls_tipos_de_documento}
return render(request, 'app_cliente/frontend/ingreso.html', context)
我的问题是在视图中返回什么?
按照设置“context-processor.py”的步骤后,在这个文件中,我有:
路径:app_cliente/context-processor.py
文件:context-processor.py:
请注意,我只返回上下文
from app_cliente.forms import ClienteCreationForm
from django.views import View
from nucleo.models.tipo_documento import TipoDocumento
class RegistroClienteView(View):
def get(self, request):
ls_tipos_de_documento = TipoDocumento.objects.values_list('id', 'nombre_corto')
form = ClienteCreationForm()
context = {'form': form, 'ls_tipos_de_documento': ls_tipos_de_documento}
return context
def post(self, request):
ls_tipos_de_documento = TipoDocumento.objects.values_list('id', 'nombre_corto')
form = ClienteCreationForm(request.POST)
if form.is_valid():
form.save()
context = {'form': form}
return context
context = {'form': form, 'ls_tipos_de_documento': ls_tipos_de_documento}
return context
问题:
在我的 urls.py 中,这个 View 应该从哪个 url 调用?
这是正确的方法吗?
更新 1:
让我使用 cmets 中发布的这个示例来澄清我的问题:
url(r'^any-url-i-want/$', RegistroClienteView.as_view(), name='any-name-i-want'),
这里,RegistroClienteView.as_view() 会渲染哪个模板???请记住,它只返回 context_processor.py 文件中的上下文。
【问题讨论】:
-
在您的问题中,您说您希望导航栏元素出现在所有模板中。它与上下文处理器有什么关系?
-
"在我的 urls.py 中,这个视图应该从哪个 url 调用?"你可以设置任何你想要的 url,只要你通过视图。如
url(r'^any-url-i-want/$', RegistroClienteView.as_view(), name='any-name-i-want'), -
导航栏中的 @guillermochamorro 是登录/注册表单。正如将在不同页面中一样,我想一劳永逸地在“base”.html 中调用我的视图。
-
@guillermochamorro,请参阅更新后的问题。你能解释一下吗?泰。