Django:用户配置文件的动态 URL

标签 django url django-urls

所以我正在尝试为我的用户制作一个非常传统的动态 URL 个人资料页面。所以例如。 www.website.com/profile/(用户名)

当我输入有效的用户名时,出现 NoReverseMatch 错误,但我不知道为什么。这是我的代码片段

urls.py

urlpatterns = [
url(r'^admin/', admin.site.urls),

url(r'^signup/$', accountsViews.signup, name="signup"),
url(r'^logout/$', authViews.LogoutView.as_view(), name='logout'),
url(r'^login/$', authViews.LoginView.as_view(template_name='login.html'), name="login"),
url(r'^find/$', findViews.find, name="find"),
# url(r'^profile/$', accountsViews.profile, name="profile"),
url(r'profile/(?P<username>.+)/$', accountsViews.profile, name="profile"),
url(r'^$', views.home, name="home"),]

views.py

def profile(request, username=None):
if User.objects.get(username=username):
    user = User.objects.get(username=username)
    return render(request, "profile.html", {
        "user": user,
    })
else:
    return render("User not found")

html 文件

{% if user.is_authenticated %}
                {% url 'profile' as profile_url %}
                <li {% if request.get_full_path == profile_url %}class="active"{% endif %}><a href="{% url 'profile' %}"><span class="glyphicon glyphicon-user"></span> Profile </a></li>
                <li><a href="{% url 'logout' %}"><span class="glyphicon glyphicon-log-out"></span> Log Out</a></li>
            {% endif %}

如果有帮助的话,错误消息会突出显示“{% url 'profile' %}”部分作为错误,并声称它没有反向匹配。但是,在我的 urls.py 中,您可以清楚地看到我已经完成了 name="profile"

任何帮助将不胜感激。谢谢!

最佳答案

您应该将用户名放在个人资料的url模板标签中

{% url 'profile' user.username %}

Check docs: https://docs.djangoproject.com/en/1.11/topics/http/urls/#examples

关于Django:用户配置文件的动态 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47130388/

相关文章:

用于 Web URL 的 iOS 孟加拉语文本解析器

http - 使用 HTTP POST 时在 URL 中传递参数

python - 在 Django 中模拟 POST 请求

python - 在 Django 中从 urls.py 输出文本

mysql - Docker 与 mysql 和 django。尽管进行了任何尝试,与 mysql 的连接都被拒绝

javascript - 从运行应用程序的系统访问相机

python - Django表单错误: 'QueryDict' object has no attribute 'method' when POST assigned

django - 如何在Django中建立Gmail样式搜寻?

python - 如何在 Python 中获取文件的内容类型? (带网址..)

python - "Import Error: No module named urls"与 Django 1.8 和 Rest Framework 3.7