簡體   English   中英

NoReverseMatch at /login - LOGIN_URL 或反向函數出錯?

[英]NoReverseMatch at /login - error with LOGIN_URL or reverse function?

我正在 Django 中開發一個應用程序。

我正在開發用戶身份驗證。

我在路徑中有一個registration.html和一個login.html模板:模板 > 身份驗證

一切,包括注冊功能,工作正常,但當我嘗試訪問登錄模板時,瀏覽器返回:

在 /login 處無反向匹配

“app”不是注冊的命名空間

我敢打賭問題出在我在settings.py 中添加的LOGIN_URL以啟用身份驗證系統(我正在學習教程)。 實際上,所有其他視圖都可以正常工作,只是指向login.html 的視圖不行。

以下是我與身份驗證系統相關的所有內容:

在我的settings.py 中

LOGIN_URL = '/login'

在我的base.html 中

          {% if user.is_authenticated %}

          <li class="nav-item dropdown">

            <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">{{ user_form.username }}</a>
            
            <div class="dropdown-menu">

              <a class="dropdown-item" href="">profilo</a>                  
              <a class="dropdown-item" href="{% url 'logout' %}">Log out</a>

            </div>
            
          </li>

          {% elif not user.is_authenticated %}

          <li class="nav-item dropdown">

            <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Login</a>
            
            <div class="dropdown-menu">

              <a class="dropdown-item" href="{% url 'registration' %}">Registrati</a>
              <a class="dropdown-item" href="{% url 'login' %}">Accedi</a>

            </div>

          </li>

          {% endif %}

在我的身份驗證> login.html 中

{% extends 'base.html'%} <!-- vuol dire inserisci qui la navigation toolbar contenuta in base -->

{% block content %}

    <h1>Login</h1>
    
    <br>

    <div class="jumbotron">

        <form action="{% url 'app:login' %}" method="post">
            {% csrf_token %}

            <label for="username">Username:</label>
            <input type="text" name="username" value="" placeholder="nome utente">

            <label for="password">Password:</label>
            <input type="password" name="password" value="" placeholder="password">

            <input type="submit" name="" value="Login">

        </form>

    </div>
    


{% load static %}  <!-- Qui il tag è obbligatorio nonostante sia stato inserito dentro base.html -->

<!-- CSS -->
{% comment %} <link rel="stylesheet" type="text/css" href={% static "css/file.css" %}> {% endcomment %}

<!-- Javascript -->
{% comment %} <script type="text/javascript" src={% static "js/file.js" %}></script> {% endcomment %}

{% endblock %}

在我的應用程序 > urls.py 中,在urlpatterns列表中:

path('authentication/registration', views_users_authentication.registration, name="registration"),
path('login', views_users_authentication.user_login, name="login"),

在我的項目 > urls.py 中,在urlpatterns列表中:

path('admin/', admin.site.urls),
path('', include('app.urls')),

然后我有一個單獨的表來包含與身份驗證系統相關的視圖函數,即views_users_authentication.py ,其中包含:

def registration(request):

    registered = False

    # se l'utente ha lanciato il post
    if request.method=="POST":

        print("post eseguito!")
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileInfoForm(data=request.POST)

        # condizione di validità del form
        if user_form.is_valid() and profile_form.is_valid():
            
            print("form validi!")

            user = user_form.save()
            user.set_password(user.password) # questa linea hasha la pasword
            user.save()
            # registra l'utente

            profile = profile_form.save(commit=False)
            profile.user = user

            registered=True

            print("Utente registrato con successo!")

            # condizione per registrare l'utente
            if 'profile_pic' in request.FILES:
                profile.profile_pic = request.FILES['profile_pic']
                print("Acquisita la fotografia dell'utente!")
            
            profile.save()
            # attenzione al salvataggio dei form e dei modelli che sono due cose diverse
                # registra le info aggiuntive

                

        else:
            print("Registrazione fallita:")
            print(user_form.errors, profile_form.errors)

    else:
        user_form = UserForm()
        profile_form = UserProfileInfoForm()

    context_dict = {'user_form':user_form, 'profile_form':profile_form, 'registered':registered}

    return render(request, 'authentication/registration.html', context_dict)


def user_login(request):

    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")

        user = authenticate(username=username, password=password)

        if user:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect(reverse('home'))

            else:
                HttpResponse("Account non attivo")
        
        else:
            print("qualcuno ha cercato di loggarsi e ha fallito")
            print("Username: {} and password {}".format(username,password))
            return HttpResponse("Inseriti parametri non validi per il login!")

    else:
        return render(request, "authentication/login.html", {})

在您的login.html您應該只使用login作為 url 名稱而不是app:login

<form action="{% url 'login' %}" method="post">

由於您沒有在 urlpatterns.py 文件中指定命名空間。 如果你想使用app命名空間,你可以像這樣更改 urlpattern:

path('', include('app.urls', namespace='app')),

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM