如何在a标签中通过URL的name属性输出路径?及在views.py中打印该值
Great questions! Let's walk through each solution with clear examples tailored to your setup.
1. Using the URL name in an <a> tag in templates
You already know about Django's {% url %} template tag, and embedding it directly into the href attribute of your <a> tag is straightforward. Here's how to do it:
<a href="{% url 'login_register' %}">Go to Login/Register</a>
This will render as something like <a href="/login-register/">Go to Login/Register</a> (depending on your project's root URL configuration). The best part here is that if you ever change the actual URL path in urls.py (say, to /auth/login/), you won't have to update this template—Django will automatically use the new path as long as the name attribute stays the same.
If your URL required parameters (like a user ID), you could add them inside the template tag like this:
<!-- Example for a URL with a positional argument --> <a href="{% url 'user_profile' user.id %}">View Profile</a>
2. Printing the URL path in views.py
To get the URL path associated with the login_register name in your view code, use Django's reverse() function from the django.urls module. Here's a step-by-step example:
First, import the function at the top of your views.py:
from django.urls import reverse from django.shortcuts import render def some_view(request): # Get the URL path using its name login_register_url = reverse('login_register') # Print it to the console or use it in your logic print(f"Login/Register URL path: {login_register_url}") # ... rest of your view code return render(request, 'some_template.html')
When you run this, the console will output something like Login/Register URL path: /login-register/.
Just like with the template tag, if your URL had parameters, you'd pass them using args or kwargs:
# Example for a URL with a keyword argument profile_url = reverse('user_profile', kwargs={'user_id': 123})
内容的提问来源于stack exchange,提问作者Username




