How to pass a variable to urls.py - regex

I have a database 'artist' with one table : 'name', 'style'.
Users can add any names for an artist.
I would like to pass an argument to url in my template, like this :
<a href="{% url 'webgui.views.music' artist.name %}" style="margin-bottom: 3px" type="button"
But is it possible to set dynamically the URL with the argument 'artist.name' (in urls.py) ?
My urls.py actually :
url(r'^music/(\d+)/$', 'webgui.views.music'),
Maybe I need to change '\d+' by another regexp ??

Instead of using
url(r'^music/(\d+)/$', 'webgui.views.music'),
because d+ stands for digits, you should use
url(r'^music/?P<artist_name>[a-zA-Z0-9 \'&-]/$', 'webgui.views.music')
Don't forget to modify function
def whatever_named_it(request, artist_name):
...
Update: In template you should use
{% url 'webgui.views.music' artist_name=artist.name %}
because we are using named arguments.
Extra: If you are going to allow any text for artist's name, I would recommend you using slug to avoid spaces in URL. That would make it better to read, search engine friendly and avoid of insane user input. When programming web-app never trust user input ... ever.
For "slugified" name urls would be:
url(r'^music/(?P<slug>[\w-]+)/$', 'webgui.views.music')

Related

How to pass a template tag from one template to another in django 2

I am new to Django, and template tags and HTML and have a template where I use a for loop to fill out bootstrap cards from a database. In the model I has a field Resume_link that has a PDF file. All I want to is have the PDF file displayed in a different template file and not in the card where it is too small to read. (Since I am in the loop when someone clicks the link, I just want the specific resume connected to that card to be shown in the new template.) So all I think I should need to do is somehow either pass the the index of the loop, or another variable that identifies the correct database entry. But I think I am missing something fundamental and don't understand how to pass the value of a template tag in one template another template. Is there some way to pass a variable along with the url to a view so the variable can be used to make a new template tag in the desired template?
{% for key in myres %}
...fill out other parts of cards and create the below link...
<a href="{% url "show_pdf" %}" style="font-size: 20px">
{% endfor %}
where show_pdf is the view where I want to show the whole PDF file.
and that template show_pdf is
What I would like to do is be able to pass the key.Resume_link.url, or if not that the pk for that database table to the show_pdf template.
The view for show_pdf is
def show_pdf(request):
template = 'show_pdf.html'
myres=Research.objects.all()
context = {'myres': myres}
return render(request,'mainapp/show_pdf.html', context)
you can pass the current pdf id in the url and access it.
def show_pdf(request, pdf_id):
template = 'show_pdf.html'
myres=Research.objects.get(id=pdf_id)
context = {'myres': myres}
return render(request,'mainapp/show_pdf.html', context)
In you urls.py you must write like this
path('show_pdf/?P<int:pdf_id>/', views.show_pdf, name="show_pdf")
In HTML write <a href="{% url "show_pdf" key.id %}">
Instead of:
<a href="{% url "show_pdf" %}">
... you would include a parameter, e.g.:
<a href="{% url "show_pdf" pdf_id %}">
The resulting URL would now be formatted as indicated by the corresponding urlconf entry, for instance:
http://my.web.site/resumes/show_pdf/1343
(if pdf_id = 1343 ...)
You must specify as many parameters as the corresponding urlconf entry expects, and you may use either positional or keyword syntax (but not both).
Then, when the user clicks on the link, the View specified in that urlconf will get control, and it will have the specified parameter value (1343 ...) as one of its arguments. You'd select the PDF and send it to the template to be properly presented to the user.

Django: How to make this GET request with a hyperlink?

So if I want a user's name to link to it's profile, I want the link to contain the user's first name and last name in GET form...Do I just hard-code this into the link, or is there a more elegant way of coding this? Here is hard-coded:
<p>
<li role="presentation" class="active">{{ user.fname }}
</li>
</p>
Yes, the more elegant way would be to set up a route that takes, for example, the user's ID (pk) and use either a DetailView set up for the User model or a function view that accepts the ID and retrieves the relevant user. Passing in the first and last name directly means you need to query on both of them (after pulling them out of the querystring) rather than simply querying on the ID as it's passed to you (after the framework politely checks its type, provided you've set up the route correctly).
So your route would look something like url(r'^profile/(?P<pk>\d+)/$', ProfileView.as_view(), name='profile') and your template tag would look something like {% url 'profile' user.id %}.

Django : model instance url is appending to the current url

i have some link in a template to which i want to point to particular url.
template is accessed at url : loacalhost:8000/account/profile
{% for poll in voted_poll_list %}
<h4>{{ poll.title }} </h4>
{% endfor %}
in models.py i have created the url for the poll objects to be used in a template.
def link_url(self):
return "polls/"+ "allcat/" +str(self.id)
the problem is when a link in template is clicked it is point to the loacalhost:8000/account/profile/polls/allcat/1 instead of loacalhost:8000/polls/allcat/1 which matches to url pattern
url(r'^polls/(\w+)/(?P<pid>[-\d]+)/', 'pollsite.views.poll_detail', name='detail_poll'),
the problem is link url of object is appended to current url. how can i avoid this ?
#garnertb 's solution works, but you should probably look into using the reverse function rather than hardcoding your url.
Something like:
return reverse('detail_poll', self.id)
This will not only take care of the leading slash, but also avoid trouble if you ever start changing your url configuration.
Try leading the url with a forward slash:
def link_url(self):
return "/polls/allcat/" +str(self.id)

identical views different URLs

I have following routs:
url(r'^future/programs/$', main.programs, {'period': 'future'}),
url(r'^past/programs/$', main.programs, {'period': 'past'}),
When I try to display link in template, using template tag url like this
{% url main.views.main.programs %}
I always get link /past/programs/. When I try like this
{% url main.views.main.programs period="future" %}
I get an error:
Caught NoReverseMatch while rendering: Reverse for
'main.views.main.programs' with arguments '()' and keyword arguments
'{'period': u'future'}' not found.
How i can display link to /future/programs/?
I think you might want to approach it with one single url pattern:
url(r'^(?P(<period>[\w]+)/programs/$', main.views.programs),
and in your view:
def programs(request, period):
if period == 'future':
...
elif period == 'past':
...
and in templates:
{% url main.views.main.programs period="future" %}
In your approach, you are mistaking the forward flow with the reverse flow, i.e. the extra keyword arguments of the url conf with the keyword arguments that are passed to match a pattern.
The former is extra data you are allowed to pass to a view when it is matched (i.e. when a user goes to /future/programs/, the pattern is matched and period=future is passed to the view), the latter is the actual data used to match the url (i.e. the period=future is passed to the reverse() function which tries to match a pattern that excepts those keyword arguments - which you haven't outlined)
Edit:
A more appropriate pattern to use in your url would be something like:
url(r'^(?P(<period>past|future)/programs/$', main.views.programs),
where the selection could only be 'past' or 'future'. This is fine for incoming urls, but django's reverse() function (which is used in the url template tag) can't handle alternative choices:
https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse
The main restriction at the moment is that the pattern cannot contain alternative choices using the vertical bar ("|") character.
I would rather assign each url a name:
url(r'^future/programs/$', main.programs,
{'period': 'future'},
name='future_programs'),
url(r'^past/programs/$', main.programs,
{'period': 'past'},
name='past_programs'),
And to display the link in your template:
Past programs: {% url past_programs %}
Future programs: {% url future_programs %}
I think this solution is better because if you just have two options for that view, you can forget about passing parameters and validating them.
Now, if those two options (future, past) can grow into several more, the other solution would be better, but I think this is not the case.

Using string literals as parameters to template tags in Django templates

One of the things I find myself doing often is passing string literals as parameters to template tags or functions; for instance:
{% url my-url 'my_param' %}
Unfortunately, the django template engine doesn't let you do this. So I find myself doing this a lot in my view code:
my_context_dict['MY_PARAM'] = 'my_param'
and then in my view code:
{% url my-url MY_PARAM %}
Or creating a series of URL mappings, which I personally try to avoid.
Is it possible to use a string literal in Django templates? Or possibly a more elegant solution? I haven't seen anything on here or in the documentation.
This feels wrong but is right.
text
The nested ""'s don't seem like they should work. They do. The Django {% %} material is simply pulled out of the HTML without regard for surrounding context. So the "duplicated" "'s aren't really duplicated at all.
Use double quotes instead of single quotes:
{% url my_view "my_param" %}
Very wierd - I have a django project that uses single quotes to pass a string value and it functions just fine.
<a href="{% url categories 'vendor' %}"</a>
<a href="{% url categories 'crew' %}"</a>
On further investigation it turns out this has changed in django 1.5. It now requires the quotes even around the url pattern name.