Django 如何检查用户是否在路径中

Django how to check if user is in path

我做了一个唯一的 url 我想检查 acutal url 是否包含 uid 所以我做了一个 if 语句,在我的情况下它总是错误的所以我可以改变它工作并检查路径是否包含 uid。

views.py

@login_required(login_url='home:login')
def ChangeEmailView(request, token):
   packet = get_object_or_404(TempUrl, user=request.user)
   token = packet.uid
   if request.path == str(token):
       if request.method == 'POST':
           objects = User.objects.get(email = request.user.email)
           form = EmailChangingForm(request.POST, instance=objects)
           if form.is_valid():
               form.save()
               
           return redirect('home:profilesettings')
           
       else:
           objects = User.objects.get(email = request.user.email)
           form = EmailChangingForm(request.POST, instance=objects)
           packet = get_object_or_404(TempUrl, user=request.user)
           token = packet.uid
       
   else:  
       print('site wasnt found')
       objects = User.objects.get(email = request.user.email)
       form = EmailChangingForm(request.POST, instance=objects)
       packet = get_object_or_404(TempUrl, user=request.user)
       token = packet.uid
       return redirect('home:index')
   context = {'form': form, 'token': token}
   return render(request, 'home/email_settings.html', context)

鉴于 URL 绑定到 ChangeEmailView 是由

设置的
path('settings/email/changeemail/<str:token>', views.ChangeEmailView , name="changeemail")

那么 if request.path == str(token) 总是 False 因为 request.path 包括完整的 URL 路径(即 /settings/email/changeemail/)而不仅仅是你的令牌。

我想你想要以下内容

@login_required(login_url='home:login')
def ChangeEmailView(request, token):
   packet = get_object_or_404(TempUrl, user=request.user)
   site_token = packet.uid
   if token == str(site_token):
       if request.method == 'POST':
           objects = User.objects.get(email = request.user.email)
           form = EmailChangingForm(request.POST, instance=objects)
           if form.is_valid():
               form.save()
               
           return redirect('home:profilesettings')
           
       else:
           objects = User.objects.get(email = request.user.email)
           form = EmailChangingForm(request.POST, instance=objects)
           packet = get_object_or_404(TempUrl, user=request.user)
           token = packet.uid
       
   else:  
       print('site wasnt found')
       objects = User.objects.get(email = request.user.email)
       form = EmailChangingForm(request.POST, instance=objects)
       packet = get_object_or_404(TempUrl, user=request.user)
       token = packet.uid
       return redirect('home:index')
   context = {'form': form, 'token': token}
   return render(request, 'home/email_settings.html', context)

Django 将提取 URL 路径的最后一个条目并作为 token 参数传递给您的视图,您可以使用它来检查您的 uid 是否存在。