我试图实现LoginRequiredMixin。例如,如果用户进入/ post / 6并且他没有登录,则会将其重定向到/ auth / login /?next = / post / 6。我试图创建一个函数,将用户重定向到/ post / *(根据url中的next)或者如果url中没有next。我试图在GET请求中获取一个url参数,将其保存到CBV成员,然后在post中使用它。但由于某些原因,它实际上并没有得到拯救。这是我的一段代码:
class LoginView(View):
redirect_to = ''
def post(self, request, *args, **kwargs):
user = authenticate(username=request.POST['login'], password=request.POST['password'])
print(self.redirect_to) # It's equal to '' here
if user is not None:
login(request, user)
else:
print("Account doesn't exists!")
return HttpResponseRedirect(reverse('blog:index'))
def get(self, request, *args, **kwargs):
self.redirect_to = 'edited'
form = RegistrationForm()
return render(request, 'authorization/login.html', {
'form': form
})
也许有其他解决方案?提前谢谢!
答案 0 :(得分:0)
我认为您最安全的选择是使用braces
:
$ pip install braces
LoginRequiredMixin
几乎旨在复制CBV的login_required
装饰器功能:
from django.views.generic import TemplateView
from braces.views import LoginRequiredMixin
class SomeSecretView(LoginRequiredMixin, TemplateView):
template_name = "path/to/template.html"
login_url = "/login/"
def get(self, request):
return self.render_to_response({})