主页面访问问题
在完成了之前的代码之后,进行简单的测试。刷新一下页面会发现跳回到了登录页面。
可是我明明做了会话的保存呀,怎么又给我退回去了。
看一下我们登录部分的urls和views可以看到,只输入ip+端口的url进行访问会触发get请求
1def get(self, request):2 return render(request, 'login/index.html')
一触发get请求,得了页面被重新渲染了一遍,又到了index.html去了。
新建app
为了摆脱这个坑,还有就是为了让代码有一定的条理,我们新建一个app。
新建app
和之前的loginapp一样,我们把它拉到apps文件夹下,然后去settings里面进行配置
在INSTALLED_APPS中加入workspace
1INSTALLED_APPS = [ 2 'django.contrib.admin', 3 'django.contrib.auth', 4 'django.contrib.contenttypes', 5 'django.contrib.sessions', 6 'django.contrib.messages', 7 'django.contrib.staticfiles', 8 'login', 9 'workspace'10]
在workspace里面新建urls.py文件
然后在主的urls.py中加入path('',include('workspace.urls')),
使用git进行版本管理,所以本次新增进行了一次提交,提交的哈希值为:
1b29558e0a309aa725608972edb51d481c3f9ec3。
通过github可以很容易的看出文件的树状结构,修改的内容等。一般开发者最终开发出来的代码都很难阅读,但是遵循版本提交的路径来看的话,就会发现大家也都是一步步走过来的。从开始的漏洞百出,到之后的行云流水。(虽然我还很菜,但记录每次的想法,一点点改变都是进步)多人协作的版本管理可能学习成本有点高,但是如果项目就只有一个人的话还是很容易的。希望大家能将自己的学习成功及时记录/分享。
设置登录后跳转
因为我们登录页面的登录是一个button,所以我们无法使用直接链接到正确页面的方式。
我们采用重定向的方式完成登录。
既然登录后要跳转至首页,那就把登录的post请求的渲染页面给修改掉:
1从 return render(request,'index/index.html')2改为 return redirect(reverse("index"))
为了可以正确跳转,我们还需要先编写index相关的代码
1from django.shortcuts import render2from django.views import View3class IndexView(View):4 def get(self, request):5 return render(request, 'index/index.html')
编写类视图,并定义它的get方法为渲染index.html页面
它的url为:
1from django.urls import path2from . import views3urlpatterns = [4 path('index/', views.IndexView.as_view(), name='index'),5]
因为没加权限校验,所以我们直接访问http://127.0.0.1:8000/index/就能进入首页。
查看跳转过程
我们可以打开F12进行抓包,可以看到登录的POST请求完成之后会的状态码是302,
登录跳转
1def redirect(to, *args, permanent=False, **kwargs): 2 """ 3 Return an HttpResponseRedirect to the appropriate URL for the arguments 4 passed. 5 6 The arguments could be: 7 8 * A model: the model's `get_absolute_url()` function will be called. 910 * A view name, possibly with arguments: `urls.reverse()` will be used11 to reverse-resolve the name.1213 * A URL, which will be used as-is for the redirect location.1415 Issues a temporary redirect by default; pass permanent=True to issue a16 permanent redirect.17 """18 redirect_class = HttpResponsePermanentRedirect if permanent else HttpResponseRedirect19 return redirect_class(resolve_url(to, *args, **kwargs))
跳转
从源码粗略可以看出跳转的状态码应该是302或者是301,因为我们没有传入permanet所以是302。
git地址:https://github.com/zx490336534/Zxapitest
欢迎关注我的公众号zx94_11