【问题标题】:get_context_data() missing 1 required positional argument: 'request'get_context_data() 缺少 1 个必需的位置参数:“请求”
【发布时间】:2021-08-30 04:40:22
【问题描述】:

我遇到了一个问题,当我尝试从基于类的视图重定向时,在 def get_context_data 上没有“重定向”,我得到了像“str”对象没有属性“用户”这样的错误。 所以我认为解决这个问题的最好方法是在我的 get_context_data 上添加请求作为参数。 但我得到标题错误。

更新:正如你告诉我的,我必须使用 self.request,我得到的错误是: 'str' 对象没有属性 'user' 我将返回 url 更新为重定向到每个用户家的方法 'redirect'

这是我的看法:

@login_required
def redirect(request):
    '''Redirige al home de cada usuario luego de validar las credenciales'''
    user=request.user
    grupo=request.user.groups.values_list('name', flat=True).first()
    print("nombre grupo: ",grupo)
    if len(grupo)>0:
        redireccion='inventario:'+grupo.lower()+"-inventarios"
        return HttpResponseRedirect(reverse_lazy(redireccion))
    '''Anula sesión si postulante no se encuentra presente en clase'''
    do_logout(request)
    return render(request, "account/login.html")

class EstandarViews:
'''Vistas usuario Estandar'''

@staticmethod
def estandar_home(request):
    ''' Vista del home de estandar '''
    return render(request, "pages/editor-estandar/home.html")


class EditorEstandarView(LoginRequiredMixin, TemplateView):
template_name = "pages/editor-estandar/estandar.html"

    def get_context_data(self, request, **kwargs):
    user = self.request.user
    print("usuario: ", user)
    if not self.request.user.groups.filter(name="Editor-Estandar").exists():
        print("no puedes estar aqui")
        return redirect('redirect)

    context = super().get_context_data(**kwargs)
    context["sedes"] = Sede.objects.values("nombre", "id")
    context["recintos"] = Recinto.objects.values("id", "codigo", "nombre")
    context["carreras"] = Carrera.objects.values("id", "codigo", "nombre")
    return context

    editor_estandar_view = EditorEstandarView.as_view()

URLS.PY

app_name = "inventario"

general_urlpatterns = [
    path("", view=home_view, name="home"),
]

editor_estandar_urlpatterns = [
    path("estandar-inventario/", view=editor_estandar_view, name="editor-estandar-inventarios"),
]


editor_inventario_urlpatterns = [
    path("estandar-inventario/", view=editor_inventario_view, name="editor-inventario-inventarios"),
]

visualizador_urlpatterns = [
    path("estandar-inventario/", view=visualizador_inventario_view, name="visualizador-inventarios"),
]

urlpatterns = [
# path("", include(general_urlpatterns)),
    path("home/", include(general_urlpatterns)),
    path('', LoginView.as_view(redirect_authenticated_user=True,template_name="account/login.html"), name="login"),
    path('redirect/', redirect, name='redirect'),
    path("editor-estandar-inventarios/", include(editor_estandar_urlpatterns)),
    path("editor-inventario-inventarios/", include(editor_inventario_urlpatterns)),
    path("visualizador/", include(visualizador_urlpatterns)),
    path("mantenedor-productos/", view=mantenedor_productos_view, name="mantenedor-productos"),
    path("mantenedor-laboratorios/", view=mantenedor_recintos_view, name="mantenedor-recintos"),
    path("mantenedor-sedes/", view=mantenedor_sedes_view, name="mantenedor-sedes"),
    path("mantenedor-carreras/", view=mantenedor_carreras_view, name="mantenedor-carreras"),
    path("mantenedor-proveedor/", view=mantenedor_proveedores_view, name="mantenedor-proveedores"),
    path("mantenedor-usuario/", view=mantenedor_usuarios_view, name="mantenedor-usuarios"),
    path("estandar-inventario/", view=estandar_inventario_view, name="estandar-inventarios"),
    path("inventario/", view=inventario_view, name="inventario"),
    path("cotizaciones/", view=cotizaciones_view, name="cotizaciones"),
    path("cotizaciones-por-producto/", view=cotizaciones_por_producto_view, name="cotizaciones-por-producto"),
    path("ficha-presentacion/", view=ficha_presentacion_view, name="ficha-presentacion"),
    path("sugerencias/", view=sugerencias_view, name="sugerencias"),
    path("cumplimiento/", view=cumplimiento_estandar_view, name="cumplimiento"),
    path("faltantes/", view=faltantes_estandar_view, name="faltantes"),
    path("sugerencias-reporte/", view=sugerencias_estandar_view, name="repo_sugerencias"),

    # path("~update/", view=user_update_view, name="update"),
    # path("<str:username>/", view=user_detail_view, name="detail"),
]

【问题讨论】:

  • 不,它没有:/
  • 嗯,你的问题从字面上说你得到了错误get_context_data() missing 1 required positional argument: 'request'。重复的目标,甚至 do 下面的答案都解决了这个错误。尽管您的代码中有更多错误,但最好单独询问它们。作为提示,尽管您定义了函数 redirect(request)(您期望请求对象的位置)并使用 string redirect('redirect)... 字典(上下文)不是一些响应对象...
  • 也许如果我重定向到另一个可以从自身生成请求的 url 函数,然后返回请求会起作用?

标签: python-3.x django django-views


【解决方案1】:

get_context_data 方法在其参数中不接受请求。

应该是get_context_data(self, **kwargs)

如果您想访问 get_context_data 中的请求,只需使用 self.request

【讨论】:

    【解决方案2】:

    在您的意见中删除请求,然后尝试

    class EditorEstandarView(LoginRequiredMixin, TemplateView):
    template_name = "pages/editor-estandar/estandar.html"
    
        def get_context_data(self, **kwargs):
        user = self.request.user
        print("usuario: ", user)
        if not self.request.user.groups.filter(name="Editor-Estandar").exists():
            print("no puedes estar aqui")
            return redirect('/home/')
    
        context = super().get_context_data(**kwargs)
        context["sedes"] = Sede.objects.values("nombre", "id")
        context["recintos"] = Recinto.objects.values("id", "codigo", "nombre")
        context["carreras"] = Carrera.objects.values("id", "codigo", "nombre")
        return context
    
        editor_estandar_view = EditorEstandarView.as_view()
    

    get_context_data 是一个方法,因此当前实例总是由通常命名为 self 的解释器隐式传递给它。

    请阅读有关视图的完整文档https://docs.djangoproject.com/en/3.2/topics/class-based-views/#:~:text=A%20view%20is%20a%20callable,by%20harnessing%20inheritance%20and%20mixins

    【讨论】:

    • get_context_data 是一个方法,因此当前实例总是由通常命名为self 的解释器隐式传递给它。无论如何,您的回答都会导致错误,因为 OP 在方法中使用 self...
    • 我更新了我的问题,现在真正的问题是我无法重定向到“重定向”或任何 url 路径
    • @Nuevakenia 也添加你的 urls.py 文件
    • 我建议重定向到任何 url 路径你必须像这样重定向 return redirect('appname:urlpathname') 如果它仍然不适合你尝试这样添加完整的错误和追溯
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 2018-01-24
    • 2020-05-07
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多