Redirecting after login in django rest framework

Viewed 3688

I am trying to redirect to a particular url after the user logs in. I am using django rest framework's built-in user authentication. I have tried the following code:

In urls.py, I have the following:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^register/$',views.CreateUserView.as_view(),name='user'),
    url(r'^api-auth/',include('rest_framework.urls',namespace='rest_framework')),
    url(r'^',include(router.urls)),
]

In settings.py, I have included the following:

LOGIN_REDIRECT_URL = '/task'

I am on the following page 'localhost/register' and after creating a user and logging in, it redirects to same 'localhost/register page'. How do I redirect to the homepage? Is there anything I am missing?

2 Answers

try this login view

from django.contrib.auth.forms import AuthenticationForm

def Login(request):
if request.method == 'POST':

    #AuthenticationForm_can_also_be_used__

    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        form = login(request,user)
        messages.success(request, f' wecome {username} !!')
        return redirect('index')
    else:
        messages.info(request, f'account done not exit plz sign in')
form = AuthenticationForm()
return render(request, 'user/login.html', {'form':form,'title':'log in'})

add this to views.py and set any redirect this is a part of my project in case you need to see full file link

In your views.py after registration you should redirect to login page or your home page.

def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            # REDIRECT here
            return redirect('login')
    else:
        form = UserRegisterForm()
    return render(request, 'users/register.html', {'form': form})

Also you can use redirection like this:

<your_app>/urls.py

from . import views

app_name = 'your_app_name'

urlpatterns = [
    path('', views.index, name='index'),

in your settings.py add LOGIN_REDIRECT_URL = '<your_app_name>:index'

Related