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.
Related
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'm trying to pass an empty parameter to render a template but I can not achieve this I do not know if the problem is in urls.py or views, I really appreciate a hand.
Urls
url(r'^hola/(\b[a-z\.-]+)$', views.hola, name='hola'),
Views
def hola(request, varr = ''):
#val = val
pregunta = Datos_usuario_DB.objects.all().order_by('-id').filter(activo="1")[:15]
plantilla = {'': 'index.html', 'nosotros': 'nosotros.html'}
return render(request, plantilla['%s' % varr], {'pregunta': pregunta})
When I access to hola/ it says that the website does not exist.
If you want /hola/ to work, it's easy to add another URL pattern:
url(r'^hola/$', views.hola, name='hola'),
url(r'^hola/([a-z\.-]+)$', views.hola, name='hola'),
It's not clear to me why you have \b in the regex, so I removed it.
your urls is not contains hola/ entry, so It returns error.
If you want to call hola/, you need to add url in urls.py
I have a problem with redirection in Django :
my view
def myP(request,namep):
return render(request,"site/myP.html")
def create(request):
nom="alaild"
....
return redirect(reverse(myP,namep=nom))
urls to this views
url(r'^create$', 'create', name='create'),
url(r'^myp/(?P<namep>\d+)','myP', name="myp"),
I have this error :
reverse() got an unexpected keyword argument 'name'
I want create view redirects to myP view but myP view have 1 argument and I don't know how make...
May be
reverse(myP, kwargs={'namep': nom})
In your view, nom is a string, but in your url pattern you are using \d+ (one or more digits).
A common approach is to accept a 'slug' which can contain letters, digits, underscores and hyphens:
url(r'^myp/(?P<namep>[\w-]+)','myP', name="myp"),
Then you need to fix the syntax of your reverse call. Either of the following should work.
reverse(myP, kwargs={'namep': nom})
reverse(myP, args=(nom,))
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')
I have a url url(r'^dev/(?P<file_name>[-\w]+)', dev_static),
in my view function dev_view(request,file_name), I want to get 'abc/file.js' as slug file_name.
how do i pass 'abc/file.js' as the whole file_name? now the slug only get 'abc', it will cut everything after '/'
Change your url pattern like this:
url(r'^dev/(?P<file_name>[-\w/.]+)', dev_static)
That is, by adding / and . in the list of allowed characters, now it will match abc/file.js.