使用模型创建房间 link

Creating room link with models

我一直在使用 Django 和 Channels 开发运动队应用程序,其中房间名称(包含在 link 中)对应于 'team code'(主键)。用户通过外键连接到团队,我试图找到一种方法,在用户登录后将用户重定向到他们团队的聊天室 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"),
]

如有任何帮助,我们将不胜感激

您重定向到:

return redirect('room'<b>, room_name=user.team_id</b>)

其中 'room' 是视图的 名称 room_name=user.team_id 是 [=28= 中 room_name 参数的值].

然而,您应该重新排序 url,使 room 视图位于最后,否则如果您访问 logout/,它将触发 room 视图 logout 作为 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'),
    #      ↓ <i>before</i> the room view
    path('logout/', logout_user, name="logout"),
    path('<str:room_name>/', room, name='room'),
]