后置反转(NoReverseMatch)

2024-09-29 19:18:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python的初学者。在这种情况下,我只想回到细节上来(索引.html)更新数据后的个人资料。我得到了错误的NoReverseMatch。你知道吗

型号.py

from django.contrib.auth.models import User
from modulos.administracao.models import *
from django.urls import reverse


class PessoaVinculada(models.Model):
    class Meta:
        ordering = ['nome']
        verbose_name = 'Pessoa Vinculada á Unidade'
        verbose_name_plural = 'Pessoas Vinculadas á Unidade'

    user = models.OneToOneField(User, unique=True, related_name='pessoa_vinculada', on_delete=models.CASCADE)
    nome = models.CharField(max_length=200, null=True, verbose_name='Nome completo')
    apelido_em_uso = models.CharField(max_length=20, null=True, verbose_name='Apelido em uso')
    genero = models.ForeignKey(Generos, null=True, verbose_name='Género', on_delete=models.SET_NULL)
    acesso_a_aplicacao = models.BooleanField(default=True, verbose_name='Acesso à aplicação')

    def __str__(self):
        return '{}'.format(self.nome)

    def get_success_url(self, **kwargs):
        # obj = form.instance or self.object
        return reverse("profile", kwargs={'pk': self.id})

    def nim(self):
        return '{}'.format(self.user.username)

    def nome_apelido_em_uso(self):
        if self.nome and self.apelido_em_uso:
            n = self.nome.split()
            return '{} {}'.format(n[0], self.apelido_em_uso)
        else:
            return '{}'.format(self.nome)

视图.py

from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.contrib.auth.decorators import login_required
from modulos.gestao.forms import *


@login_required(login_url="/login/")
def estado_maior_seccao_pessoal_pessoal_pessoas_vinculadas_dados_biograficos_elementos_gerais(request, pk=None):
    context = {}
    context['user'] = get_object_or_404(User, id=pk)
    context['pessoa_vinculada'] = get_object_or_404(PessoaVinculada, user_id=pk)
    context['pessoa_vinculada_identificacao'] = PessoaVinculadaIdentificacao.objects.filter(user_id=pk)
    context['pessoa_vinculada_foto'] = PessoaVinculadaFoto.objects.filter(user_id=pk)

    return render(request, 'gestao/estado_maior/seccao_pessoal/pessoal/pessoas_vinculadas/dados_biograficos/geral/index.html', context)


@login_required(login_url="/login/")
def estado_maior_seccao_pessoal_pessoal_pessoas_vinculadas_dados_biograficos_elementos_gerais_editar(request, pk=None):
    user = get_object_or_404(User, id=pk)
    pessoa_vinculada_identificacao = PessoaVinculadaIdentificacao.objects.filter(user_id=pk)
    pessoa_vinculada_foto = PessoaVinculadaFoto.objects.filter(user_id=pk)
    pessoa_vinculada = get_object_or_404(PessoaVinculada, id=pk)
    if request.method == 'POST':
        user_form = PessoaVinculadaForm(request.POST, instance=pessoa_vinculada)
        if user_form.is_valid():
            user_form.save()
            return HttpResponseRedirect(reverse("estado_maior_seccao_pessoal_pessoal_pessoas_vinculadas_dados_biograficos_elementos_gerais"))
        else:
            context = {
                'user': user,
                'pessoa_vinculada_identificacao': pessoa_vinculada_identificacao,
                'pessoa_vinculada_foto': pessoa_vinculada_foto,
                'pessoa_vinculada': pessoa_vinculada,
                'user_form': user_form,
            }
            return render(request, 'gestao/estado_maior/seccao_pessoal/pessoal/pessoas_vinculadas/dados_biograficos/geral/editar.html', context)
    else:
        user_form = PessoaVinculadaForm(instance=pessoa_vinculada)
        context = {
            'user': user,
            'pessoa_vinculada_identificacao': pessoa_vinculada_identificacao,
            'pessoa_vinculada_foto': pessoa_vinculada_foto,
            'pessoa_vinculada': pessoa_vinculada,
            'user_form': user_form,
        }
        return render(request, 'gestao/estado_maior/seccao_pessoal/pessoal/pessoas_vinculadas/dados_biograficos/geral/editar.html', context)

表单.py

从django导入表单 从模.pessoas.vinculadas.模型导入*

class PessoaVinculadaForm(forms.ModelForm):
    class Meta:
        model = PessoaVinculada
        fields = [
            'user',
            'nome',
            'apelido_em_uso',
            'genero',
            'acesso_a_aplicacao',
        ]

网址.py

from modulos.gestao import views
from django.urls import path

urlpatterns = [
    path('estado_maior/seccao_pessoal/pessoal/pessoas_vinculadas/dados_biograficos/<int:pk>/geral/', views.estado_maior_seccao_pessoal_pessoal_pessoas_vinculadas_dados_biograficos_elementos_gerais, name='estado_maior_seccao_pessoal_pessoal_pessoas_vinculadas_dados_biograficos_elementos_gerais'),
    path('estado_maior/seccao_pessoal/pessoal/pessoas_vinculadas/dados_biograficos/geral/<int:pk>/editar/', views.estado_maior_seccao_pessoal_pessoal_pessoas_vinculadas_dados_biograficos_elementos_gerais_editar, name='estado_maior_seccao_pessoal_pessoal_pessoas_vinculadas_dados_biograficos_elementos_gerais_editar'),
]

编辑.html

        <form method="post" action="" enctype="multipart/form-data">
            {% csrf_token %}
            <div class="row">
                <div class="hidden">
                    {{ user_form.user }}
                </div>
            </div>
            <br>
            <div class="row">
                <div class="col-sm-5">
                    {{ user_form.nome|as_crispy_field }}
                </div>
                <div class="col-sm-2">
                    {{ user_form.apelido_em_uso|as_crispy_field }}
                </div>
            </div>
            <br>
            <div class="row">
                <div class="col-sm-2">
                    {{ user_form.genero|as_crispy_field }}
                </div>
            </div>
            <br>
            <div class="row">
                <div class="col-sm-2">
                    {{ user_form.acesso_a_aplicacao|as_crispy_field }}
                </div>
            </div>
            <br>
            <div style="border-bottom: 1px solid rgba(0, 0, 0, 0.3);">&nbsp;</div>
            <br>
            <button class="btn btn-success btn-sm" type="submit" class="button">Guardar</button>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <a href="/gestao/estado_maior/seccao_pessoal/pessoal/pessoas_vinculadas/dados_biograficos/{{ user.id }}/geral/"
               class="btn btn-danger btn-sm"
               type="button">Cancelar</a>
        </form>

错误:

NoReverseMatch at /gestao/estado_maior/seccao_pessoal/pessoal/pessoas_vinculadas/dados_biograficos/geral/1/editar/
Reverse for 'estado_maior_seccao_pessoal_pessoal_pessoas_vinculadas_dados_biograficos_elementos_gerais' with no arguments not found. 1 pattern(s) tried: ['gestao\\/estado_maior\\/seccao_pessoal\\/pessoal\\/pessoas_vinculadas\\/dados_biograficos\\/(?P<pk>[0-9]+)\\/geral\\/$']
Request Method: POST
Request URL:    http://127.0.0.1:8000/gestao/estado_maior/seccao_pessoal/pessoal/pessoas_vinculadas/dados_biograficos/geral/1/editar/
Django Version: 2.0.7
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'estado_maior_seccao_pessoal_pessoal_pessoas_vinculadas_dados_biograficos_elementos_gerais' with no arguments not found. 1 pattern(s) tried: ['gestao\\/estado_maior\\/seccao_pessoal\\/pessoal\\/pessoas_vinculadas\\/dados_biograficos\\/(?P<pk>[0-9]+)\\/geral\\/$']
Exception Location: F:\Work\RTm_Project\GitLab\Python\gesrhu\venv\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 636
Python Executable:  F:\Work\RTm_Project\GitLab\Python\gesrhu\venv\Scripts\python.exe
Python Version: 3.6.6
Python Path:    
['F:\\Work\\RTm_Project\\GitLab\\Python\\gesrhu',
 'F:\\Work\\RTm_Project\\GitLab\\Python\\gesrhu',
 'F:\\Work\\RTm_Project\\GitLab\\Python\\gesrhu\\venv\\Scripts\\python36.zip',
 'C:\\Users\\fonse\\AppData\\Local\\Programs\\Python\\Python36-32\\DLLs',
 'C:\\Users\\fonse\\AppData\\Local\\Programs\\Python\\Python36-32\\lib',
 'C:\\Users\\fonse\\AppData\\Local\\Programs\\Python\\Python36-32',
 'F:\\Work\\RTm_Project\\GitLab\\Python\\gesrhu\\venv',
 'F:\\Work\\RTm_Project\\GitLab\\Python\\gesrhu\\venv\\lib\\site-packages',
 'F:\\Work\\RTm_Project\\GitLab\\Python\\gesrhu\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg',
 'F:\\Work\\RTm_Project\\GitLab\\Python\\gesrhu\\venv\\lib\\site-packages\\pip-10.0.1-py3.6.egg',
 'C:\\Program Files\\JetBrains\\PyCharm '
 '2018.1.4\\helpers\\pycharm_matplotlib_backend']
Server time:    Mon, 16 Jul 2018 17:57:09 +0100

回溯:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/gestao/estado_maior/seccao_pessoal/pessoal/pessoas_vinculadas/dados_biograficos/geral/1/editar/

Django Version: 2.0.7
Python Version: 3.6.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'modulos.autenticacao',
 'modulos.administracao',
 'modulos.pessoas.vinculadas',
 'modulos.pessoas.naovinculadas',
 'modulos.gestao',
 'smart_selects',
 'crispy_forms',
 'django_tables2',
 'mptt',
 'django_cleanup',
 'bootstrap3',
 'auditlog']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'auditlog.middleware.AuditlogMiddleware']



Traceback:

File "F:\Work\RTm_Project\GitLab\Python\gesrhu\venv\lib\site-packages\django\core\handlers\exception.py" in inner
  35.             response = get_response(request)

File "F:\Work\RTm_Project\GitLab\Python\gesrhu\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "F:\Work\RTm_Project\GitLab\Python\gesrhu\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "F:\Work\RTm_Project\GitLab\Python\gesrhu\venv\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  21.                 return view_func(request, *args, **kwargs)

File "F:\Work\RTm_Project\GitLab\Python\gesrhu\modulos\gestao\views.py" in estado_maior_seccao_pessoal_pessoal_pessoas_vinculadas_dados_biograficos_elementos_gerais_editar
  65.             return HttpResponseRedirect(reverse("estado_maior_seccao_pessoal_pessoal_pessoas_vinculadas_dados_biograficos_elementos_gerais"))

File "F:\Work\RTm_Project\GitLab\Python\gesrhu\venv\lib\site-packages\django\urls\base.py" in reverse
  90.     return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))

File "F:\Work\RTm_Project\GitLab\Python\gesrhu\venv\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix
  636.         raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /gestao/estado_maior/seccao_pessoal/pessoal/pessoas_vinculadas/dados_biograficos/geral/1/editar/
Exception Value: Reverse for 'estado_maior_seccao_pessoal_pessoal_pessoas_vinculadas_dados_biograficos_elementos_gerais' with no arguments not found. 1 pattern(s) tried: ['gestao\\/estado_maior\\/seccao_pessoal\\/pessoal\\/pessoas_vinculadas\\/dados_biograficos\\/(?P<pk>[0-9]+)\\/geral\\/$']

提前谢谢!你知道吗


Tags: djangodivformclassuserdadosestadomaior
2条回答

您忘记添加参数pk,因为url模式匹配的是path('too/long/path/to/<int:pk>/geral/'

return HttpResponseRedirect(reverse("estado_maior_......",kwargs={'pk':pk}))

首先,你真的不需要给你的url和视图起这么长的名字。名称不需要反映URL的结构;11个元素太长。你知道吗

无论如何,错误应该很清楚:您请求的是一个包含pk参数的URL,但您没有提供该参数。您可能希望返回到最初请求的用户的视图,因此需要传递该参数:

return HttpResponseRedirect(reverse("estado...gerais", kwargs={'pk': pk}))

可缩短为:

return redirect("estado...gerais", pk=pk)

但是,请,请,改变那些名字。你知道吗

相关问题 更多 >

    热门问题