Answer the question
In order to leave comments, you need to log in
How to correctly redirect the user to the main page after login and logout in Django?
Good day to all, dear members of the forum!) I
started learning Django just recently, I got the idea to make a simple blog for a start, where the main page will immediately display a list of articles from the database, sorted by date (i.e. when you click on the link my_site.ru /
the main_views.index view immediately fires , which loads all the articles into the
template logout in Django?
here is the project structure:
my_project
|
|--- articles
|
|--- accounts
code my_project/urls.py
from django.contrib import admin
from django.urls import path, include
from . import views as main_views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('', main_views.index),
path('admin/', admin.site.urls),
path('articles/', include('articles.urls')),
path('accounts/', include('accounts.urls')),
]
from . import views
from django.urls import path
urlpatterns = [
path('login', views.login),
path('logout', views.logout,
]
from django.shortcuts import render, redirect
from django.contrib import auth
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None and user.is_active:
auth.login(request, user)
context = {'user': user}
return render(request, 'index.html', context)
else:
context = {'user': None}
return render(request, 'index.html', context)
def logout(request):
auth.logout(request)
return render(request, 'index.html')
]
{% if user.is_authenticated %}
<div class="user"> Привет, {{ user.get_full_name }}!
<form action="accounts/logout" method="post"> {% csrf_token %}
<input type="submit" value="Выйти" />
</form>
</div>
{% else %}
{% if form.errors %}
<p class="error">Сожалеем, вы неправильно ввели логин или пароль</p>
{% endif %}
<form action="accounts/login" method="post">{% csrf_token %}
<label for="username">Логин:</label>
<input type="text" name="username" value="" id="username">
<label for="password">Пароль:</label>
<input type="password" name="password" value="" id="password">
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
{% endif %}
Page not found (404)
Request Method: POST
Request URL: http://127.0.0.1:8000/accounts/accounts/logout
Answer the question
In order to leave comments, you need to log in
Use the url tag in your templates and return a response with redirect in login/logout
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question