0

Suppose I have this model:

Class animals(models.Model):
   name = models.CharField(max_length = 20)

and I make 3 objects of it, say ob1, ob2, ob3 with ob1.name = cat, ob2.name = dog, ob3.name = cow

Now if I have a url like this www.domain.com/cator www.domain.com/dog, How to capture /cat or /dogfrom the url and check against the names of objects of class animal?

I am trying to implement a view function that takes a parameter from the url, eg: object.name, and execute according to that object.

Any help is appreciated.

0

1 Answer 1

1

Use named groups.

It’s possible to use named regular-expression groups to capture URL bits and pass them as keyword arguments to a view.

urls.py:

from django.conf.urls import patterns, url

urlpatterns = patterns('',
    url(r'^(?P<name>\w+)/$', 'my_view'),)

views.py:

def my_view(request, name=None):
    # get a model instance
    animal = animals.objects.get(name=name)

Hope that helps.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. But is there a way to detect objects from urls? im trying something like this in urls.py, url(animal.objects.value_list('name'), include('animalapp.urls'). I want to match the /cat or /dog from url and match it with animal.objects.value_list('name') list. Is this possible?
@HHH how does this answer not provide what you're looking for?
Generally catch all pattern like this url(r'^(?P<name>\w+)/$', 'my_view') is bad idea. If it is possible change it to something like url(r'^animal/(?P<name>\w+)/$', 'my_view'). Otherwise if you must have it /cat, /cow, etc. you may have to move part of your url routing logic in my_view(request, name) which also is bad idea

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.