ohjuny
ohjuny

Reputation: 481

Django: dynamic URL for user profiles

So I'm trying to make a pretty conventional dynamic URL profile pages for my users. So eg. www.website.com/profile/(username)

I am getting an error of NoReverseMatch when I enter a valid username, and I do not know why. Here are snippets of my code

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 file

{% 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 %}

Also it if it helps, the error message is highlighting the "{% url 'profile' %}" part as the error, and claiming that it does not have a reverse match. However, in my urls.py, you can clearly see that I have done name="profile"

Any help would be greatly appreciated. Thank you!

Upvotes: 3

Views: 1744

Answers (1)

zhiqiang huang
zhiqiang huang

Reputation: 361

You should put the username in url template tag of profile

{% url 'profile' user.username %}

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

Upvotes: 4

Related Questions