Oraz
Oraz

Reputation: 33

How to correctly write url for #hashtag in Django

I want to insert data with modal form and show it on current page. Page already show data on table and modal form, now i need to add modal form to urls.py.

 path('viewpost/#add_data_Modal', views.createpost, name='createpost'),

Upvotes: 1

Views: 1052

Answers (2)

palAlaa
palAlaa

Reputation: 9858

I find another simpler way to do it, I suggest passing the hashtag as a query string to the view then reverse redirect there, so

in urls.py keep it the simple

path('', views.home, name='main-home')

in home function in views.py

@csrf_exempt
def home(request):
    hashtag = request.GET.get("hashtag", "")
    if hashtag:
        return HttpResponseRedirect(reverse("main-home") + "#{0}".format(hashtag))
    context = {}
    return render(request, 'index.html', context)

and in the html u can pass any hashtag you want


<a class="nav-link" href="{% url 'main-home' %}?hashtag=team" >Team</a>

<a class="nav-link" href="{% url 'main-home' %}?hashtag=contact">Contact</a>
                

Upvotes: 1

Dev Catalin
Dev Catalin

Reputation: 1325

You could use a RedirectView for this:

from django.views.generic import RedirectView
from django.urls import reverse


class ViewpostRedirectView(RedirectView):
    def get_redirect_url(*args, **kwargs):
        hash_part = "add_data_Modal"  # the data you want to add to the hash part
        return reverse("createpost") + "#{0}".format(hash_part)

Then in your urls.py you would have something lime this:

path('viewpost/', views.createpost, name='createpost'),
path('viewpost/modal/', views.ViewpostRedirectView.as_view(), name='createpost_modal')

The viewpost/modal/ url will redirect to the viewpost/ url with the hash part appended to it.

Upvotes: 1

Related Questions