我做了一个小项目。用户首先登录,然后他被重定向到主页。但是,如果用户尚未登录,那么如果我们粘贴该主页的 url,该主页也会打开。我已经尝试了网上给出的很多东西,但它不起作用。这是我的 urls.pyfrom django.conf.urls import urlfrom django.contrib import adminfrom blog import viewsurlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.login, name='login'), url(r'^register/$', views.register, name='register'), url(r'^home/$', views.home, name='home'), url(r'^javaq/$', views.javaq, name='javaq'), url(r'^javar/$', views.javar, name='javar'), url(r'^csq/$', views.csq, name='csq'), url(r'^csr/$', views.csr, name='csr'), url(r'^cq/$', views.cq, name='cq'), url(r'^cr/$', views.cr, name='cr'), url(r'^cppq/$', views.cppq, name='cppq'), url(r'^cppr/$', views.cppr, name='cppr'), url(r'^pythonq/$', views.pythonq, name='pythonq'), url(r'^pythonr/$', views.pythonr, name='pythonr'), url(r'^mini/$', views.mini, name='mini'),]这是我的view.pyfrom django.shortcuts import renderfrom .models import logininfo,CSTEST,CTEST,CPPTEST,JAVATEST,PYTHONTEST,resultfrom django.http import HttpResponsefrom django.shortcuts import renderfrom django.contrib.auth.decorators import login_requiredfrom django.views.decorators.cache import cache_controlimport datetimedef login(request): if request.method=="POST": user_name=request.POST.get("username") sid=request.POST.get("sid") password=request.POST.get("password") article = logininfo() article.user_name = user_name article.sid = sid article.password = password article.save() return render(request,'login.html')def home(request): if request.method=="POST": sid=request.POST.get("sid") password=request.POST.get("password") request.session['sd'] = sid user_obj=logininfo.objects.filter(sid=sid,password=password) if user_obj.count()==0: return HttpResponse("Sorry wrong password try again") return render(request,'home.html') def register(request): return render(request,'register.html')
3 回答
慕田峪9158850
TA贡献1794条经验 获得超7个赞
慕妹3146593
TA贡献1820条经验 获得超9个赞
您可以在页面上使用 django 内置登录身份验证
@login_required(login_url='/url where you want user to redirect/')
def myview(request):
do something
return something #returns when user is logged in
一只名叫tom的猫
TA贡献1906条经验 获得超3个赞
也许你应该看看Django Stronghold。
按照说明在您的设置中启用此功能,默认情况下每个视图都会变为私有。
然后,您可以像这样装饰您希望公开访问的任何函数:
@public
def register():
# Do something
这可能是初学者的方法,因为您现在所做的(在主视图中处理身份验证逻辑)意味着您将为每个单独的视图重复此操作,如果您遗漏了某些内容,应用程序最终可能会公开。
添加回答
举报
0/150
提交
取消