Reputation: 71
I am creating a webapp where i have sections like home,profile,and on home page there are several posts which are written by users. But when i go to the posts and from there if i have to return back to home page,it says page not found. it takes me to the following link http://127.0.0.1:8000/post/4/home
. but i want to go to http://127.0.0.1:8000/home
. How to do this
<li> <a href="profile">Profile </a></li>
<li> <a href="logout">Logout</a> </li>
<li> <a href="password_change">Password change</a> </li>
<li> <a href="home">home </a>
</li>
my views.py of homepage
def homep(request):
context = {
'posts':post.objects.all()
}
return render (request,'welcome.html',context)
my urls.py
path('',views.index,name='index'),
path('login',views.login_view,name='login'),
path('register',views.register,name="Login now"),
path('logout',views.logout_view,name='logout'),
path('profile', views.profile,name='profile'),
path('home',PostListView.as_view(),name='home'),
path('edit_profile',views.profile_change,name='profile_change'),
path('post/<int:pk>/',PostDetailView.as_view(),name ='post-detail'),
Upvotes: 1
Views: 120
Reputation: 476614
That is because it will each time append the values at the end. You can prevent that by prepending a slash, so href="/logout"
, but probably it is better to make use of the {% url … %}
template tag [Django-doc]:
<li><a href="{% url 'profile' %}">Profile </a></li>
<li><a href="{% url 'logout' %}">Logout</a></li>
<li><a href="{% url 'password_change' %}">Password change</a></li>
<li><a href="{% url 'home' %}">home</a></li>
Upvotes: 2
Reputation: 69
It is not a good practice to hardcode html links in the href , You can use Django template tags, for example
<a href="{% url 'home' %}">Home</a>
where home is the name given in the urls.py file for more info you can check here
where you can also send id's like
<a href="{% url 'post' post.id %}">Post</a>
Upvotes: 1