-1

Problem of urls in django Authentification

this is my app urls.py

from django.urls import path,  re_path
from . import views

app_name = 'music'

urlpatterns = [

    path('register/', views.register, name='register'),
    path('login_user/', views.login_user, name='login_user'),
    path('logout_user/', views.logout_user, name='logout_user'),
    #path('<int:album_id>/', views.detail, name='detail'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    #re_path(r'^(?P<album_id>[0-9]+)/$', views.detail, name='detail'),
    #path('<int:album_id>/favorite/', views.favorite, name='favorite'),
    path('album/add', views.AlbumCreate.as_view(), name='album-add'),
    path('album/<int:pk>/', views.AlbumUpdate.as_view(), name='album-update'),
    path('album/<int:pk>/delete/', views.AlbumDelete.as_view(), name='album-delete'),
    path('index/', views.IndexView.as_view(), name='index'),
    path('', views.login_user)
    # path('', views.index, name='index'),


]

this is my views.py file

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.views import generic
from django.views.generic import View
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from django.contrib.auth.decorators import login_required
from .models import Album, Song
from django.db.models import Q
from .forms import UserForm


class IndexView(generic.ListView):
    template_name = 'music/index.html'
    def get_queryset(self):
        return Album.objects.all() 

class DetailView(generic.DetailView):
    model = Album
    template_name = 'music/detail.html'


class AlbumCreate(CreateView):
    model = Album
    fields = ['artist', 'alum_title', 'genre', 'album_logo']


class AlbumUpdate(UpdateView):
    model = Album
    fields = ['artist', 'alum_title', 'genre', 'album_logo']


class AlbumDelete(DeleteView):
    model = Album
    success_url = reverse_lazy('music:index')


@login_required(login_url="/login_user/")
class UserFormView(View):
    form_class = UserForm
    template_name = 'music/registration_form.html'

    def get(self, request):
        form = self.form_class(None)
        return render(request, self.template_name,{'form':form})

    def post(self, request):
        form = self.form_class(request.POST)

        if form.is_valid():

            user = form.save(commit=False)

            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user.set_password(password)
            user.save()

            user = authenticate(username=username, password=password)

            if user is not None :
                 if user.is_active:
                     login(request, user)
                     return redirect('music:index')

            return render(request, self.template_name,{'form' : form})

        context = {
            "form": form,
        }
        return render(request, 'music/registration_form.html', context)

def logout_user(request):
    logout(request)
    form = UserForm(request.POST or None)
    context = {
        "form": form,
    }
    return render(request, 'music/login.html', context)

def login_user(request):
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                albums = Album.objects.filter(user=request.user)
                return render(request, 'music/index.html', {'albums': albums})
            else:
                return render(request, 'music/login.html', {'error_message': 'Your account has been disabled'})
        else:
            return render(request, 'music/login.html', {'error_message': 'Invalid login'})
    else:
        return render(request, 'music/login.html')


def register(request):
    form = UserForm(request.POST or None)
    if form.is_valid():
        user = form.save(commit=False)
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user.set_password(password)
        user.save()
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                albums = Album.objects.filter(user=request.user)
                return render(request, 'music/index.html', {'albums': albums})
    context = {
        "form": form,
    }
    return render(request, 'music/register.html', context)

this is my models.py file

from django.contrib.auth.models import Permission, User
from django.db import models
from django.urls import reverse


class Album(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
    artist = models.CharField(max_length=20)
    alum_title = models.CharField(max_length=20)
    genre = models.CharField(max_length=10)
    album_logo = models.FileField()

    def get_absolute_url(self):
        return reverse('music:detail', kwargs={'pk':self.pk})
    def __str__(self):
        return self.alum_title + self.artist

class Song(models.Model):
    album = models.ForeignKey(Album, on_delete=models.CASCADE)
    file_type = models.CharField(max_length=10)
    song_title = models.CharField(max_length=20)
    is_favorite = models.BooleanField(default=False)

    def __str__(self):
        return self.song_title

my problem is that when I logout and try to play with urls it logs but the user session is ended I tried to solve the problem with login_required but it didn't work can anyone help me to solve this problem ?

1 Answers1

0

I think I understand what you are asking, maybe. So when you logout and then try and access a permissions only page, you still can gain access.

First - Not sure if its an issue but I think there should be a trailing "," in your urlpatterns for login_user.

Second - If you are using the django User model, why are you creating these complicated view methods? Django can handle all that itself, it seems a mess to shove it all in the views.py file. All you should need is some html files to render it.

I would strongly suggest you look at the Setting Up Your Authentication Views part of the tutorial as it goes through an example of setting up Users really nicely and then you can remove the login and logout methods from your views.py and only have to use "@login_required" for the pages you want to restrict access to.

Let me know if this helps.

Jonnyboy
  • 136
  • 1
  • 8