您的 Jinja 语法需要稍微修改一下。如果您想在 Django 模板中检查用户是否经过身份验证,您需要按如下方式操作:
{% if request.user.is_authenticated %}
<a href="{% url 'user-logout' %}" class="appointment-btn scrollto">Logout</a>
<a href="{% url 'user-profile' %}" class="appointment-btn scrollto">Profile-{{ user.username }}</a>
{% else %}
<a href="{% url 'user-login' %}" class="appointment-btn scrollto">Sign in / Sign up</a>
{% endif %}
您忘记了模板中的请求。此外,您还可以在视图中检查用户是否已通过身份验证,如下所示:
def profile(request):
if request.user.is_authenticated:
return render(request, 'user/profile.html', {'user':request.user})
else:
return redirect('user-login')
您的 urls.py
路径有两条为空的路径。请检查一下:
from django.contrib import admin
from django.urls import path, include
from user import views as user_view
from django.contrib.auth import views as auth_views
from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
# see this one and,
path('', include('dashboard.urls')),
path('register/', user_view.register, name = 'user-register'),
path('profile/', user_view.profile, name = 'user-profile'),
# see this one
path('', auth_views.LoginView.as_view(template_name = 'user/login.html'),name='user-login'),
path('logout/', TemplateView.as_view(template_name = 'user/logout.html'),name='user-logout' ),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
我建议将其更改为其他内容,例如:
rom django.contrib import admin
from django.urls import path, include
from user import views as user_view
from django.contrib.auth import views as auth_views
from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('dashboard.urls')),
path('register/', user_view.register, name = 'user-register'),
path('profile/', user_view.profile, name = 'user-profile'),
# I'v changed this to login path
path('login/', auth_views.LoginView.as_view(template_name = 'user/login.html'),name='user-login'),
path('logout/', TemplateView.as_view(template_name = 'user/logout.html'),name='user-logout' ),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)