I want to match any url with a numeric id (various length) at the end and pass that id to a view function.
My urls are in this form:
/event/dash-separated-strings-2014-12-16-342614/
The id is 342614. The content before the date is also various.
Here is my url config:
url(r'^event/(*.-\d{4}-\d{2}-\d{2}-)(?P<event_id>\d*)/$', view_event , name='my_view_event')
The problem is that the full url is passed to my view function. What i want is the named group only. What is wrong with my config?
Try this:
url(r'^event/[\w\-]+-\d{4}-\d{2}-\d{2}-(?P<event_id>\d+)/$', view_event , name='my_view_event')
Related
I have got a question that I could not find an answer to. Is it possible in Django to create an URL path in urls.py that looks like the following?
path('article?date={some value here}/', article.site.urls)
The query string [wiki] is not part of the path, this is a sequence of key-value pairs.
In the view you can access this with request.GET which is a dictionary-like object.
You can thus define a path as:
path('article/', some_view)
and then in the view access the date with:
def some_view(request):
date = request.GET.get('date')
# …
In django web app, user may define urls with dynamic parameters, for example:
/users/:id
or
/posts/:postid/:commentid
now, I have given strings, for example:
/users/mysername <- it matches /users/:id - how can I exstract "myusername" from it?
/users/mysuername/something <- doesn't match
/posts/10/382 - match, extract two variables - postid and commentid
my models.py:
class Server(BaseModel):
url = models.CharField(verbose_name=_('URL'), max_length=64)
in my view, I want to compare request's PATH_INFO:
endpoint_url = request.META.get('PATH_INFO').lower().strip().lstrip('/')
lets say I have a Server model instance with url: /users/:someid
now, when request path is: /users/somestring0
I want to match it and extract variable someid to be "somestring0".
Parmeters may contain anything - except slash (/) probably.
How can I achieve something like that?
If these endpoints are registered in Django routes, maybe just use resolver ?
from django.urls import resolve
match = resolve(my_url)
print(match.args)
print(match.kwargs)
I have two url patterns in Django:
urlpatterns += patterns('',
url(r'^(?P<song_name>.+)-(?P<dj_slug>.+)-(?P<song_id>.+)/$', songs.dj_song, name='dj_song'),
url(r'^(?P<song_name>.+)-(?P<artist_slug>.+)-(?P<song_id>.+)/$', songs.trending_song, name='trending_song'),
)
When I visit a URL of the first pattern, it opens it correctly. However if I try and visit a URL of the second pattern, it tries to access the first view again. The variables song_name, dj_slug, artist_slugare strings and song_id is an integer.
What should be the URL patterns for such a case with similar URL structure?
Both urls use the same regex. I removed the group names and get:
url(r'^(.+)-(.+)-(.+)/$', songs.dj_song, name='dj_song'),
url(r'^(.+)-(.+)-(.+)/$', songs.trending_song, name='trending_song'),
Of course django uses the first match.
You should use different urls for different views. For example add the prefix to the second url:
url(r'^trending/(?P<song_name>.+)-(?P<artist_slug>.+)-(?P<song_id>.+)/$',
songs.trending_song, name='trending_song'),
Pretty new to Django still. I have a map that the user will click on a country. I want that link to add the country name to:
URL:
url(r'^country/(?P<name>\w+)' , 'wiki.views.country',
name = 'wiki_country'),
Then the country view will open. I want to do it this way so that I can create a dynamic country view that can populate based on the name of the country, rather than individual pages served for each country. The view looks like this so far:
def country(request, name):
country = Country.objects.get(name=name)
return render_to_response("wiki/country.html") , {'country' : country})
I don't know how to take the map, or even just a text hyperlink and pass the name into the URL.
use name url patterns.
Add named urls with argument in 'href' in templates.
{% country_object.name %}
'country_object.name' is your input argument for country function.
Django Docs reference of named urls
Trying to pass Business Name in URL in stead of ID. When I pass IDs, everything is fine.
urls.py
url(r'^(?P<name>\w+)/$', 'views.business'),
views.py
def business(request, name=1):
return render_to_response('business.html',
{'business': business.objects.get(name=name) })
template.html
Name{{ business.name }}
When I do this, it will only work for single word business name such as "Bank" however if the business has multiple words "Wells Fargo" it will not work.
My goal is to use slugify to pass short SEO friendly URL such as
http://website.com/business-name/
Thanks for your time and for your help!
Accordint to re module docs \w:
matches any alphanumeric character and the underscore
and the url you are trying to match has a dash because django's slugify method converts spaces and some non-ascii chars into dashes. So the fix consists in modifying the urls.py pattern to:
url(r'^(?P<name>[\w-]+)/$', 'views.business'),
But this isn't enough. Your current view will try to get a Business instance with the slugified name and will throw a DoesNotExists exception. So you should do one of the folowing things:
Add an slug field to your Business model which value must be slugify(business.name)
or add an id to the url, like this:
url(r'^(?P[\w-]+)/(?P\d+)/$', 'views.business'),
and modify your view to get the instance by id:
def business(request, name, obj_id):
return render_to_response('business.html', {'business': business.objects.get(id=obj_id) })
First of all, you need to allow dashes in your url configuration:
url(r'^(?P<name>[-\w]+)/$', 'views.business'),
[-\w]+ matches "alphanumeric" characters in any case, underscore (_) and a dash.
Also, in the view, you need to "unslugify" the value passed in:
def business(request, name='unknown'):
name = name.replace('-', ' ').capitalize()
return render_to_response('business.html',
{'business': business.objects.get(name=name) })
Also see:
My Django URLs not picking up dashes
docs on slugify
How do I create a slug in Django?
Hope that helps.