[英]Django/Python: How to create redirect from one view/url to another?
[英](DJANGO) How to be redirect to another URL from a view?
我是 Django 的新手,现在我在从当前视图重定向到另一个 URL 时遇到了一些问题。 在这种情况下,我想被重定向到 Spotify 登录页面。
这是我的观点:
#############################################################################
client_id = 'somestring'; # Your client id
client_secret = 'anotherstring'; # Your secret
redirect_uri = 'http://127.0.0.1:8000/callback/'; # Your redirect uri
stateKey = 'spotify_auth_state'
#############################################################################
def generateRandomString(length):
text = ''
possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
for i in range(0,length):
text += possible[math.floor(random.random() * len(possible))]
return text
##############################################################################
def login_process(request):
if request.method == 'GET':
state = generateRandomString(16)
print(str(state))
HttpResponse.set_cookie(stateKey, state)
#your application requests authorization
scope = 'user-top-read user-read-email'
return HttpResponseRedirect(request, 'https://accounts.spotify.com/authorize?' + urllib.parse.urlencode({
response_type: 'code',
client_id: client_id,
scope: scope,
redirect_uri: redirect_uri,
state: state
}), {})
def login_view(request, *args, **kwargs):
print(args, kwargs)
print(request.user)
#return HttpResponse("<h1>Hello world</h1>")
return render(request, "login.html", {})
def callback_view(request, *args, **kwargs):
return render(request, "callback.html", {})
这是我应该点击重定向的链接:
<a href="login/">Login with spotify</a>
这是我的 urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', login_view, name='login_view'),
path('login/', login_process, name = 'login'),
path('callback/', callback_view, name = 'callback_view'),
]
我得到的错误是“AttributeError at /login/'str' object has no attribute 'cookies'”,我什至不知道方法“return HttpResponseRedirect”是否是做所有这些事情的正确方法。 你能帮助我吗?
这里:
HttpResponse.set_cookie(stateKey, state)
您正在类本身上调用HttpResponse.set_cookie
,而不是在实例上,因此您会得到一个未绑定的方法,该方法需要一个实例作为第一个参数。 正确的方法实际上是首先实例化响应,然后对其调用set_cookie
:
qs = urllib.parse.urlencode({
"response_type": 'code',
"client_id": client_id,
"scope": scope,
"redirect_uri": redirect_uri,
"state": state
})
url = 'https://accounts.spotify.com/authorize?{}'.format(qs)
response = HttpResponseRedirect(request, url)
reponse.set_cookie(whatever)
return response
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.