使用 Django 为用户设置登录

Setting Up Logins For Users with Django

我正在尝试使用 Django 的内置用户身份验证为 login/allowing 用户创建帐户并登录。我认为我的网址或文件在项目中的放置位置有问题。有人可以帮忙吗?

我知道 login.html 文件应该位于名为 'registration.' 的文件夹中 我认为我的模板随后位于名为 'capstone' 的子文件夹中这一事实可能会导致问题.我只是不知道如何在有人点击登录时指向正确的文件。

在 'weather' 下的 urls.py 中,我有以下内容。在两个教程中我看到它应该说 'accounts/' 但我对为什么有点困惑。

urlpatterns = [

    path('admin/', admin.site.urls),
    path('', include('capstone.urls')), # medium site says to do this
    path('accounts/', include('django.contrib.auth.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

这是我的文件在 Visual Studio 代码中的设置方式:

现在天气不好,我有:

现在在顶峰 urls.py 下,我有:

router = routers.DefaultRouter()
router.register(r'locations', views.LocationViewSet)

urlpatterns = [


    path('accounts/', include('django.contrib.auth.urls')), 
    path('api-auth/', include('rest_framework.urls', 
    namespace='rest_framework')),
    path("", views.home, name="home"),
    path("register", views.register, name="register"),
    path("login", views.login_view, name="login"),

] + static(settings.STATIC_URL, 
document_root=settings.STATIC_ROOT)

urlpatterns += static(settings.STATIC_URL, 
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, 
document_root=settings.MEDIA_ROOT)

views.py:

def home(request):
    return render(request, "capstone/home.html")


def login_view(request):
    if request.method == "POST":

        email = request.POST["email"]
        password = request.POST["password"]
        user = authenticate(request, username=email, 
password=password)

        # Check if authentication successful
        if user is not None:
            login(request, user)
            return HttpResponseRedirect(reverse('home'))
        else:
            return render(request, "capstone/login.html", {
                "message": "Invalid email and/or password."
            })
    else:
        return render(request, "capstone/login.html")    


def register(request):
    if request.method == "POST":
        email = request.POST["email"]

        # Ensure password matches confirmation - this part works!
        password = request.POST["password"]
        confirmation = request.POST["confirmation"]
        if password != confirmation:
            return render(request, "capstone/signup.html", {
                "message": "Passwords must match."
            })

        # Attempt to create new user
        try:
            User = get_user_model()
            user = User.objects.create_user(email, email, 
password)
            user.save()
        except IntegrityError as e:
            print(e)
            return render(request, "capstone/signup.html", {
                "message": "Email address already taken."
            })
        login(request, user)
        return HttpResponseRedirect(reverse("home"))
    else:
        return render(request, "capstone/signup.html")

将路径设置为 accounts/ 允许您创建 url 例如 <your_site_name>/accounts/login https://docs.djangoproject.com/en/3.2/topics/auth/default/#module-django.contrib.auth.views

基本上 link 表明您可以免费获得 login/logout/ 和其他一些 urls/views。如果您愿意,可以将名称附加到 url 使其更长...

现在我不确定 url_conf 在哪个应用程序中,调用 path('accounts/', include('django.contrib.auth.urls')), 但我猜你在底部添加了 static_dir,它是 weather/settings.py url 会议

在settings.py中的TEMPLATES设置中。如果 APP_DIRS 为 True(默认情况下),Django 将检查调用模板的 app 目录内的模板目录。在您的情况下,它将检查 [=18 中的模板目录=] 应用程序(这是您的主要应用程序)。您需要更改目录层次结构。
使用 django.contrib.auth urls

weather
|
|--templates
      |
      |--registration
            |
            |--login.html

如果您想使用 capstone 应用程序。然后你需要移动电话 path('accounts/', include('django.contrib.auth.urls')) 到顶点应用程序。此时 URL 将变为 <your_site_name/capstone/accounts/login>

===============================
现在你有一个 login_view,名为 login,它覆盖了 django contrib 的登录视图,所以你的 heirachy 应该类似于这样的东西。

capstone
|
|--templates
    |
     |--capstone
          |
          | -- login.html

此外,仅供参考,请确保以“/”结束通往 URL 的路径。比如“登录”应该是“登录/”