Reputation: 2689
So I set up a login view, and upon successful login I'd like to go to a page of my choice by referencing another class based view. I'm not entirely sure how to achieve this.
Login view
def login_view(request):
if request.method == 'POST':
form =AuthenticationForm(data=request.POST)
if form.is_valid():
user=form.get_user()
login(request,user)
#Not sure what to do next
#return HttpResponseRedirect(reverse(request, Dashboard))?
else:
#TODO
else:
form = AuthenticationForm()
Dashboard class I'm trying to get to
class Dashboard(ListView):
model = models.Note
template_name = 'notemanager/dashboard.html'
def get_context_data(self, request,**kwargs):
context = super().get_context_data(**kwargs)
notedata = models.Note.objects.filter(added_by = User)
reminderdata = models.Reminder.objects.filter(added_by = User)
context['notes'] = notedata
context['reminder'] = reminderdata
return context
urls.py
urlpatterns = [
path('login/',views.Login.as_view(),name="login"),
path('',views.Dashboard.as_view(), name ="dash")
]
Upvotes: 1
Views: 476
Reputation: 15926
In general, the way to redirect is by using the name of the url/route for the view you are using.
So if in your urls.py
you had something like:
urlpatterns = [
re_path('^dashboard$', Dashboard.as_view(), name='dashboard'),
]
You could reuse the name
part of the route to send the user a 302 redirect using redirect
:
from django.shortcuts import redirect
def login_view(request):
if request.method == 'POST':
form =AuthenticationForm(data=request.POST)
if form.is_valid():
user=form.get_user()
login(request,user)
#Not sure what to do next
#return HttpResponseRedirect(reverse(request, Dashboard))?
return redirect('dashboard') # matches the name part of the route in urls.py
else:
#TODO
else:
form = AuthenticationForm()
n.b., you also have an error in your view. There is no request
parameter to get_context_data
, so it should look like:
class Dashboard(ListView):
model = models.Note
template_name = 'notemanager/dashboard.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
notedata = models.Note.objects.filter(added_by = User)
reminderdata = models.Reminder.objects.filter(added_by = User)
context['notes'] = notedata
context['reminder'] = reminderdata
return context
Upvotes: 2
Reputation: 1370
Add redirect in your views.py,
def login_view(request):
if request.method == 'POST':
form =AuthenticationForm(data=request.POST)
if form.is_valid():
user=form.get_user()
login(request,user)
return redirect('dash') #If you have mentioned app_name in urls.py add app_name:dash in place of dash
else:
#TODO
else:
form = AuthenticationForm()
In urls.py you have,
urlpatterns = [
path('login/',views.Login.as_view(),name="login"),
path('',views.Dashboard.as_view(), name ="dash"),
]
This will redirect users to 127.0.0.1:8000/
Upvotes: 1