Search code examples
pythondjangodjango-modelsdjango-channels

Creating room link with models


I've been developing a sports team application with Django and Channels where the room name (included in the link) corresponds to the 'team code' (Primary key). The users are connected to the teams via a foreign key and I'm trying to find a way to redirect users to their team's chat room once they log in/register.

Models.py:

class Team(models.Model):
    Name    = models.CharField(max_length=60)
    code    = models.CharField(max_length=6, blank=True, primary_key=True)

    def __str__(self):
        return self.Name

    def save(self, *args, **kwargs):   # Saves the generated Team Code to the database
        if self.code == "":
            code = generate_code()
            self.code = code
        super().save(*args, **kwargs)

class User(AbstractBaseUser, PermissionsMixin):

    USER_CHOICES = [
        ('CO', 'Coach'),
        ('PL', 'Parent'),
        ('PA', 'Player'),
        ]

    User_ID      = models.UUIDField(default=uuid.uuid4, primary_key=True)
    email        = models.EmailField(verbose_name='email', max_length=60, unique=True)
    date_joined  = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
    is_active    = models.BooleanField(default=True)   ## Everything within these comment tags
    is_admin     = models.BooleanField(default=False)  ## define the permissions
    is_staff     = models.BooleanField(default=False)  ## that the user will have unless
    is_superuser = models.BooleanField(default=False)  ## changed by the superuser/admin.
    is_coach     = models.BooleanField(default=False)
    first_name   = models.CharField(max_length=50)
    last_name    = models.CharField(max_length=50)
    team         = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL) # Ensures that the user isn't deleted when a team is deleted
    user_type    = models.CharField(choices=USER_CHOICES, default='CO', max_length=20) # Useful for when the app wants to identify who has certain permissions

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name'] # The account cannot be created if they do not give their first/last names

    def __str__(self):
        return self.first_name + " " + self.last_name # Returns the email, first name and
                                                      # last name of the user.

    def has_perm(self, perm, obj=None): # Assigns the permissions that the user has
        return self.is_admin

    def has_module_perms(self, app_label):
        return True

Views.py:

def registration_view(request):
    context = {}
    if request.POST:
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            email        = form.cleaned_data.get('email')
            first_name   = form.cleaned_data.get('first_name')
            last_name    = form.cleaned_data.get('last_name')
            raw_password = form.cleaned_data.get("password1")
            account      = authenticate(email=email, first_name=first_name, last_name=last_name, password=raw_password)

            if form.cleaned_data.get('user_type') == 'CO':
                user.is_coach = True

            login(request, account)
            return redirect('<str:room_name>/')
        else:
            context['registration_form'] = form
    else:
        form = CustomUserCreationForm
        context['registration_form'] = form
    return render(request, 'Team/register.html', context)

def room(request, room_name):
    room_name = Team.objects.values('code')
    videos = Video.objects.all()
    return render(request, 'Team/room.html', {'room_name': room_name, 'videos': videos})

urls.py:

from django.urls import path
from django.contrib.auth import views as auth_views
from TeamBuilderApp.views import index, registration_view, room, logout_user

urlpatterns = [
    path('', index, name='index'),
    path('login', auth_views.LoginView.as_view(template_name= 'Team/login.html'), name='login'),
    path('register', registration_view, name='register'),
    path('<str:room_name>/', room, name='room'),
    path("logout", logout_user, name="logout"),
]

Any help would be appreciated


Solution

  • You redirect to:

    return redirect('room', room_name=user.team_id)

    Where 'room' is the name of the view, and room_name=user.team_id the value for the room_name parameter in the url.

    You however should reorder the urls such that the room view is last, otherwise if you visit logout/ it will trigger the room view with logout as room_name:

    urlpatterns = [
        path('', index, name='index'),
        path('login/', auth_views.LoginView.as_view(template_name='Team/login.html'), name='login'),
        path('register/', registration_view, name='register'),
        #      ↓ before the room view
        path('logout/', logout_user, name="logout"),
        path('<str:room_name>/', room, name='room'),
    ]