muazfaiz
muazfaiz

Reputation: 5031

Django: Get text value of the hyperlink when hyperlink is clicked

I have a hyperlink like below and I want to get "VALUE I NEEDED" when this hyperlink is clicked

<a href='http://www.example.com'>VALUE I NEEDED</a>

In Django what I can do is the following

<a name = {{ value }} href='http://www.example.com'>{{  value }}</a>

Then in views.py i can do the following

def index(request):
    text = request.GET.get("name")
    *** SOME CODE HERE ***
    return render(request, 'index.html')

But this is not working. Anyone please help me to achieve this.

Upvotes: 0

Views: 1858

Answers (2)

Praveen Kumar
Praveen Kumar

Reputation: 959

You can use the string or data you want to extract in your url as slugs and from urls.py extract the value you added. It's easy to do.

For example:

urls.py

path('my-link/<str:value>/', views.my_link, name='my_link'),

your link

<a href="my-link/{{ value }}/">{{ value }}</a>

view.py

    def my_link(request, value):
        context = { 'value_from_link': value }
        return render(request, 'my-new-link.html', context)

here you get the value from the slug of the URL using urls.py(str:value) and pass it as a variable to views and then you can use it as you wish.

Upvotes: 0

user2390182
user2390182

Reputation: 73498

You have to append the name as a querystring to the href:

<a href="http://www.example.com?name={{ value }}">{{  value }}</a>

Then it will appear in request.GET. The name attribute that you tried works for input tags and a form submission, but still a little different:

<input name="name" value={{ value }}>

Upvotes: 3

Related Questions