【问题标题】:Django, reverse lazy gives NoReverseMatchDjango,反向懒惰给出NoReverseMatch
【发布时间】:2016-02-25 01:13:06
【问题描述】:

我正在尝试更新模型的一个字段,我已经覆盖了 updateview 中的 get_success_url 方法,但它不起作用。

class MensajeApropiado(UpdateView):
    model = Mensaje
    form_class = FormMensaje
    template_name = 'foro/msjCensura.html'

    def get_success_url(self):
        return reverse_lazy('mensajes', args=(self.object.tema.id,))

urls.py

from django.contrib.auth.decorators import login_required as LR
url(r'^mensajes/(?P<pk>\d+)/$', ListaMensajes.as_view(),  name="mensajes"),
url(r'^msjcensura/(?P<pk>\d+)/', LR(MensajeApropiado.as_view()), name="censura"),

这是模板:

{% extends "base.html" %}
{% load i18n %}


{% block content %}



Fecha en Perú: {% now "m-d-Y" %}

<div>
    <a href="{% url 'home' %}">Foros</a> > <a
        href="{% url 'temas' mensaje.tema.foro.id %}">{{ mensaje.tema.foro.titulo }}</a>
    > <a href="{% url 'mensajes' mensaje.tema.id %}">{{ mensaje.tema.titulo }}</a> > Censura del mensaje
</div>


{% if mensaje.tema.autor.user.id == request.user.id and request.user.is_authenticated %}
    Tema: {{ mensaje.tema.titulo }} - {{ mensaje.tema.fecha|date:"M-d-Y" }}
    - Autor: <a href="{% url 'editar_perfil' request.user.id %}">{{ mensaje.tema.autor }} </a>
{% else %}
    Tema: {{ mensaje.tema.titulo }} - {{ mensaje.tema.fecha|date:"M-d-Y" }}
    - Autor: <a href="{% url 'detalle_usuario' mensaje.autor.id %}">{{ mensaje.autor }} </a>
{% endif %}
<br><br>

<div id="no-more-tables">

    <table style='table-layout:fixed;width:100%' class="col-md-12 table-bordered table-striped table-condensed cf">

        <thead class="cf">
        {% with mensaje.profile_data as pdata %}
            <tr>

                <th style='width: 15%;'>
                    Autor

                </th>
                <th class="celdacontenido" style='width: 85%;'>
                    {{ mensaje.fecha|date:"M, d-Y, h:i a" }}

                </th>
            </tr>
            </thead>
            <tbody>
            <tr>
            <td data-title='Autor'>
            {% if mensaje.autor.id == request.user.id and request.user.is_authenticated %}
                <a href="{% url 'editar_perfil' request.user.id %}"> {{ mensaje.autor }} </a><br>
            {% else %}
                <a href="{% url 'detalle_usuario' mensaje.autor.id %}"> {{ mensaje.autor }} </a><br>
            {% endif %}

            {% if request.user.is_staff %} Administrador<br>
            {% else %}
                Miembro<br>
            {% endif %}

            {% if  pdata.1 %}
                <img border="0" alt="Profile Pic" src="/media/{{ pdata.1 }}"/><br>
            {% else %}
                <img border="0" alt="Profile Pic" src="/media/imagenes/nouserimg.png" height="140" width="140"/><br>
            {% endif %}

            Fecha de registro: <br> {{ mensaje.autor.date_joined|date:"M-d-Y" }} <br>
            Número de mensajes: {{ pdata.0 }}
        {% endwith %}
        </td>
        <td align="justify" class="celdacontenido" data-title='{{ mensaje.fecha|date:"m-d-Y, h:i a" }}'>
            {{ mensaje.contenido }}<br>
        </td>

        </tr>

        </tbody>
    </table>
</div>
<br>
<b>Desmarcando la casilla el mensaje se catalogará como inapropiado, caso contrario al seleccionar
    la casilla, será apropiado.</b> <br><br>

<form method="POST" action="">
    {% csrf_token %}
    Apropiado:
    {{ form.apropiado }}<br><br>
    <input class="btn btn-primary" type="submit" value="Confirmar" id="submit"/>
</form>

{% endblock %}

当我点击时

<a href="{% url 'censura' mensaje.id %}" class="apropiado">Marcar como inapropiado</a>

从我的其他模板中,它可以正常工作,我可以毫无问题地看到“censura”模板,但是当我单击提交按钮时,它会在 /msjcensura/5/ 处提供 NoReverseMatch

Reverse for 'detalle_usuario' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['usuario/(?P<pk>\\d+)/']

{% url 'detalle_usuario' mensaje.autor.id %}

我不明白这一点,我指定了其他视图('mensajes'),但它转到相同的模板(censura)。

编辑,我有网址,我忘了在问题中输入它,因为问题出在重定向和 mensaje.autor.id 返回“无”:

 url(r'^usuario/(?P<pk>\d+)/', LR(DetalleUsuario.as_view()), name="detalle_usuario"),

还有观点:

class DetalleUsuario(DetailView):
model = PerfilUsuario
template_name = "foro/detalleUsuario.html"

【问题讨论】:

  • mensaje.autormensaje.autor.id 均为无。如果你打印出mensaje.autor,你会得到什么?
  • 我已经更改了代码,我正在使用两个视图: MensajeCensura(request, **kwargs) 来呈现模板和 ConfirmarCensura(request) 来更新字段,现在它可以工作了,我知道这是不是问题的解决方案,但我需要这个项目在星期二工作
  • 你没有detalle_usuario url
  • 您好,我已添加该信息

标签: python django django-views


【解决方案1】:

reverse() 用于基于函数的视图,而 reverselazy() 用于基于类的视图。

例子:

从get_success_url()方法调用django反向功能。

class MensajeApropiado(UpdateView):
    model = Mensaje
    form_class = FormMensaje
    template_name = 'foro/msjCensura.html'

    def get_success_url(self):
        return reverse('mensajes', args=(self.object.tema.id,))

从success_url参数调用。

class MensajeApropiado(UpdateView):
    model = Mensaje
    form_class = FormMensaje
    template_name = 'foro/msjCensura.html'
    success_url = reverse_lazy('mensajes', args=(self.object.tema.id,))

这是因为类属性是在导入时评估的,reverse_lazy() 处理从基于类的视图中的导入加载过程,以及从基于类的视图或基于函数的视图的方法中的 reverse() 处理加载的过程。何时或如何发生这种情况的答案存在于 python 导入系统的深处。

另请参阅此答案:Difference between reverse() and reverse_lazy() in Django

【讨论】:

    【解决方案2】:

    试试

    {% url 'detalle_usuario' pk=mensaje.autor.id %}

    这将有助于定位正确的 url,因为您的 url 配置中的参数已命名。此外,mensaje.autor.id 似乎是None。你能尝试调试一下mensaje.autor 存在并且有一个id 吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-20
      • 2023-03-21
      • 2019-12-15
      • 1970-01-01
      • 2013-10-05
      • 2010-10-08
      • 1970-01-01
      • 2013-10-22
      相关资源
      最近更新 更多