1

у меня есть в login, logout, registration. Хотел бы узнать, как сделать перенаправление(редирект) на ту же страницу, с которой пользователь входит/регается/выходит?

urls.py

from django.urls import path
from django.contrib.auth.views import LogoutView

from .views import *

urlpatterns = [
    path("", BaseView.as_view(), name='base'),
    path('users/', UserView.as_view(), name='users'),
    path("users/<slug:slug>/", UserDetailView.as_view(), name='user_detail'),
    path("news/", NewsView.as_view(), name='news'),
    path("news/<slug:slug>/", NewsDetailView.as_view(), name='news_detail'),
    path('comments/<int:pk>/', AddComments.as_view(), name='add_comments'),
    path('teams/', TeamView.as_view(), name='teams'),
    path("team/<slug:slug>/", TeamDetailView.as_view(), name='team_detail'),
    path('login/', LoginView.as_view(), name='login'),
    path('logout/', LogoutView.as_view(next_page='/'), name='logout'),
    path('registration/', RegistrationView.as_view(), name='registration'),

]

views.py

class LoginView(Author, View):

    def get(self, request, *args, **kwargs):
        form = LoginForm(request.POST or None)
        author = Author.objects.all()
        context = {'form': form, 'sdr': author}
        return render(request, 'login.html', context)

    def post(self, request, *args, **kwargs):
        form = LoginForm(request.POST or None)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                return HttpResponseRedirect('/')
        context = {'form': form}
        return render(request, 'login.html', context)


class RegistrationView(View):

    def get(self, request, *args, **kwargs):
        form = RegistrationForm(request.POST or None)
        author = Author.objects.all()
        context = {'form': form, 'sdr': author}
        return render(request, 'registration.html', context)

    def post(self, request, *args, **kwargs):
        form = RegistrationForm(request.POST or None)
        if form.is_valid():
            new_user = form.save(commit=False)
            new_user.username = form.cleaned_data['username']
            new_user.email = form.cleaned_data['email']
            new_user.first_name = form.cleaned_data['first_name']
            new_user.last_name = form.cleaned_data['last_name']
            new_user.save()
            new_user.set_password(form.cleaned_data['password'])
            new_user.save()
            Author.objects.create(
                first_name=new_user,
                last_name=new_user,
                nickname=new_user,
                url=new_user,
            )
            user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])
            login(request, user)
            return HttpResponseRedirect('/')
        context = {'form': form}
        return render(request, 'registration.html', context)

1 ответ 1

0
  1. В шаблоне

<form action="/login?next={{request.path}}" id="login_form" method="post" class="form-signin">

  1. Во views
   if request.method=='POST':
      redirect_to = request.POST.get('next', '')
      # create login form...
      # if valid login credentials have been entered:
         return HttpResponseRedirect(redirect_to)  
   #...
   return render_to_response('login.html', locals())```

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.