41
I need to add login, logout, and registration functionality to my Django app. What is the best approach?
Loading...
Q&A · Answered
I need to add login, logout, and registration functionality to my Django app. What is the best approach?
Accepted answer
# urls.py
from django.contrib.auth import views as auth_views
urlpatterns = [
path('login/', auth_views.LoginView.as_view(), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]
from django.contrib.auth.forms import UserCreationForm
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect('home')
else:
form = UserCreationForm()
return render(request, 'registration/register.html', {'form': form})
from django.contrib.auth.decorators import login_required
@login_required
def dashboard(request):
return render(request, 'dashboard.html')Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.