如何摆脱 URL 模式中的“%20Profile”

How to get rid of "%20Profile" in URL Pattern

首先,我将搜索用户,然后它会将我带到用户列表的页面上进行点击。在那之后,当我选择一个我想点击查看他们的个人资料的用户时,它应该带我到我想看到的用户页面,但那是我遇到问题的地方。 URL 模式应该是,例如 /user/MatthewRond/,但我得到 /user/MatthewRond%20Profile/,这使我无法看到 Matthew 的页面,因为 %20Profile 从未打算出现在 URL 中。如果我能弄清楚如何摆脱 %20Profile,我的问题应该就解决了。

我仔细阅读了 %20 是什么以及我从中得到了什么:它与使用和处理字母数字字符有关。无论如何 none 它帮助我弄清楚了如何删除它。至于它的代码部分,我从数据库中获取默认用户名,然后获取我从该默认用户创建的自定义配置文件。之后,我将用户名设置为我创建的自定义配置文件模型。

views.py

def profile_view(request, username, *args, **kwargs,):
    context = {}
    try:
        user = User.objects.get(username=username)
        profile = user.profile
        img = profile.uploads_set.all().order_by("-id")

        context['username'] = user.username
    except:
        return HttpResponse("Something went wrong.")
    if profile and img:
        context = {"profile": profile, "img": img}

        return render(request, "main/profile_visit.html", context)

search_results.py

<a class="profile-link" href="{% url 'profile_view' username=profile.0 %}">

urls.py

path("user/<str:username>/", views.profile_view, name = "profile_view"),

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete = models.CASCADE, null = False, blank = True)
    first_name = models.CharField(max_length = 50, null = True, blank = True)
    last_name = models.CharField(max_length = 50, null = True, blank = True)
    phone = models.CharField(max_length = 50, null = True, blank = True)
    email = models.EmailField(max_length = 50, null = True, blank = True)
    bio = models.TextField(max_length = 300, null = True, blank = True)
    profile_picture = models.ImageField(default = 'default.png', upload_to = "img/%y", null = True, blank = True)
    banner_picture = models.ImageField(default = 'bg_image.png', upload_to = "img/%y", null = True, blank = True)

    def __str__(self):
        return f'{self.user.username} Profile'

在 Raphael 的帮助下,错误将出现在配置文件 class 中。改变这个

    def __str__(self):
        return f'{self.user.username} Profile'

到此。

    def __str__(self):
        return f'{self.user.username}'

删除 space 和配置文件