使用 Django 为用户设置登录

如何解决使用 Django 为用户设置登录

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

我知道 login.html 文件应该位于名为“注册”的文件夹中。我认为我的模板位于名为“capstone”的子文件夹中的事实可能会导致问题。当有人点击登录时,我只是不知道如何指向正确的文件

在“天气”下的 urls.py 中,我有以下内容。在两个教程中,我看到它应该说“帐户/”,但我有点困惑为什么。

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 Code 中设置文件的方式:

description

enter image description here

现在在天气条件下,我有

enter image description here

现在在 capstone 下的 urls.py 下,我有

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

urlpatterns = [


    path('accounts/',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"),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,{
                "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

基本上,该链接显示您可以免费获得 login/logout/ 和其他一些网址/视图。如果您愿意,您可以将名称附加到网址以使其更长...

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

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

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 的路径。像“登录”应该是“登录/”

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?