django redirect after login not working «next» not posting? [duplicate]
I have a login page which is working fine with the exception of the redirect to the referrer page. The user gets an email with a direct link within the app, they (in this example) are not logged in already and are redirected to the login page. After successful login the user is redirected to a hardcoded path. See example below.
URL in email: http://localhost:8000/issueapp/1628/view/22
URL of login page: http://localhost:8000/login?next=/issueapp/1628/view/22
Login view (with hardcoded redirect):
Login view (with «next» redirect):
The above view results in an exception «Key ‘next’ not found in » The form does not appear to be posting the «next» variable, even though its there in the url and in the form. I have searched and looked everywhere and cant figure out why its not working. Any ideas?
Additional reference:
EDIT: The below is the code which is now working for me (thanks to the help of Paulo Bu)! **
5 Answers 5
You have to declare the html form action like this in order to your views work.
There, if there is a next variable then you include in the url for retrieve it as a get parameter. If not, the form doesn’t include it.
This is the best approach, but you may also fix this in your views by requesting the next from the POST dictionary like this:
Normally, in the template you would do something like this:
Django redirect после входа в систему не работает «далее» не публикуется? [дубликат]
этот вопрос уже есть ответ здесь:
у меня есть страница входа в систему, которая работает нормально, за исключением редиректа на страницу реферера. Пользователь получает электронное письмо с прямой ссылкой в приложении, они (в этот пример) еще не вошли в систему и перенаправляются на страницу входа в систему. После успешного входа пользователь перенаправляется на жестко закодированный путь. См. пример ниже.
URL в электронной почте: http://localhost:8000/issueapp/1628/view/22
URL страницы входа в систему: http://localhost:8000/login?next=/issueapp/1628/view/22
просмотр входа (с жестко закодированным перенаправлением):
вид входа в систему (с перенаправлением» next»):
вышеуказанное представление приводит к исключению «Key ‘next’ not found in » в форме не отображается сообщение » далее» переменная, хотя она есть в url и в форме. Я искал и искал везде и не могу понять, почему это не работает. Есть идеи?
дополнительная ссылка:
шаблон входа в систему:
EDIT: ниже приведен код, который теперь работает для меня (благодаря помощи Paulo Bu)! **
Шаблон Входа В Систему:
5 ответов
вы должны объявить html-форму action как это для того, чтобы ваш вид работы.
там, если есть next переменная, то вы включаете в url для получения его в качестве параметра get. Если нет, то форма не включает его.
это лучший подход, но вы также можете исправить это в своих представлениях, запросив next С POST словарь такой:
обычно в шаблоне вы бы сделали что-то вроде это:
надеюсь, что это помогает!
короче
Я бы определил в вашем представлении функцию next_page = request.GET[‘next’] и затем перенаправить на него return HttpResponseRedirect(next_page) поэтому вам никогда не нужно менять шаблоны; просто установите @login_required и ты в порядке.
например:
settings.py
urls.py
views.py
Если вы хотите быть более общим, вы можете просто сделать что-то вроде этого, которое передает любой из параметров GET при публикации формы:
вот ссылка рассказывает о том же
Примечание:
вы можно получить текущий url с помощью request.path С view также.
спасибо буфер. Я просто скопировал и вставил ваш комментарий, попробовав его сам в своем собственном коде.
Django, redirect all non-authenticated users to landing page
I have a django website with many urls and views. Now I have asked to redirect all non-authenticated users to a certain landing page. So, all views must check if user.is_authenticated() and return to a new set of landing pages.
Can it be done in a pretty way, instead of messing with my views.py / urls.py that much?
9 Answers 9
There is a simpler way to do this, just add the «login_url» parameter to @login_required and if the user is not login he will be redirected to the login page. You can find it here
You can use Middleware.
Something like this will check user auth every request:
Also, don’t forget to enable it in settings.py
another option is to add it to your urls.py patterns, see this answer
As of Django 1.10, the custom middleware classes must implement the new style syntax. You can use the following class to verify that the user is logged in while trying to access any views.
This can be done with middleware.
I’ve found a really nifty djangosnippet that does exactly what you are asking for. You can find it here, and it looks like:




