search_view()缺少1个必需的位置参数:“slug”

2024-05-17 19:44:24 发布

您现在位置:Python中文网/ 问答频道 /正文

错误

在/chat/search/
处键入错误 search_view()缺少1个必需的位置参数:“slug”
请求方式:POST
请求URL:http://127.0.0.1:8000/chat/search/
Django版本:3.0.7 异常类型:TypeError
异常值:
search_view()缺少1个必需的位置参数:“slug”

我的型号:

class UserProfile(models.Model)
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    slug = models.SlugField(blank=True)
    image = models.ImageField(default='face.jpg', upload_to='images/avtar')
    friends = models.ManyToManyField("UserProfile", blank= True)
    
    def __str__(self):
        return self.user.username

    def get_absolute_url(self):
        return "/chat/{}".format(self.slug)
    
    def last_seen(self):
        return cache.get('last_seen_%s' % self.user.username)
    
def post_save_user_model_receiver(sender, instance, created, *args, **kwargs):
    if created:
        try:
            Profile.objects.create(user=instance)
        except:
            pass

post_save.connect(post_save_user_model_receiver, sender=settings.AUTH_USER_MODEL)

我的网址:

url(r'^(?P<slug>[\w-]+)/$',search_view),
url(r'^friend-request/send/(?P<id>[\w-]+)/$', send_friend_request),
url(r'^friend-request/cancel/(?P<id>[\w-]+)/$', cancel_friend_request),

我的观点:

def search_view(request, slug):

    p = UserProfile.objects.filter(slug=slug).first()
    u = p.user;print(u)
    sent_friend_requests = FriendRequest.objects.filter(from_user=p.user)
    rec_friend_requests = FriendRequest.objects.filter(to_user=p.user)
    friends = p.friends.all()
    # is this user our friend
    button_status = 'none'
    if p not in request.user.profile.friends.all():
        button_status = 'not_friend'
    
        # if we have sent him a friend request
        if len(FriendRequest.objects.filter(
            from_user=request.user).filter(to_user=p.user)) == 1:
                button_status = 'friend_request_sent'
    
    if request.method =='POST':
        query = request.POST.get('search')
        results = User.objects.filter(username__contains=query) 
    
    context = {
        'results':results,
        'u': u,
        'button_status': button_status,
        'friends_list': friends,
        'sent_friend_requests': sent_friend_requests,
        'rec_friend_requests': rec_friend_requests
    }

    return render(request, 'chat/search.html', context)

Tags: selffriendsearchifobjectsmodelsrequestdef
2条回答

视图函数search_view(request, slug)正在函数定义中查找在请求URL http://127.0.0.1:8000/chat/search/中找不到的slug参数

因此,请求URL应该是:http://127.0.0.1:8000/chat/search/some_slug而不是http://127.0.0.1:8000/chat/search/。将slug变量添加到URL的末尾

您的url中有一个变量:url(r'^(?P[\w-]+)/$',search_view),您需要在请求url中使用这个变量:http://127.0.0.1:8000/chat/search/,但它不在那里,这就是这个错误告诉您的

相关问题 更多 >