Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map two urls to one view?

This is my class from models.py:

class Person(models.Model):
    name = models.CharField(max_length=64)
    persnr = models.AutoField(primary_key=True)

This is my view:

def show_person(request, persnr):
    pers = get_object_or_404(Person, pk=persnr)
    context={'pers':pers}
    return render(request, 'company/person.html', context)

This is my url:

url(r'^show_person/(?P<persnr>\d+)', "company.views.show_person", name='show_person'),

How can I get to the same view (show_person) with these two urls:

server/show_person/(persnr)

server/show_person/(name)
like image 735
Dannad Avatar asked Mar 03 '17 09:03

Dannad


2 Answers

A slightly different approach would be to accept two separate arguments, one for the pk and one for the name:

url(r'^show_person/(?P<persnr>\d+)', "company.views.show_person", name='show_person'),
url(r'^show_person/(?P<name>\w+)', "company.views.show_person", name='show_person'),

def show_person(request, persnr=None, name=None):
    if persnr is not None:
        pers = get_object_or_404(Person, pk=persnr)
    elif name is not None:
        pers = get_object_or_404(Person, name=name)
    else:
        raise Http404
like image 93
Daniel Roseman Avatar answered Oct 03 '22 23:10

Daniel Roseman


url(r'^show_person/(?P<persnr>.*)', "company.views.show_person", name='show_person'),

def show_person(request, persnr):
    per = Person.objects.filter(Q(name=persnr)|Q(persnr=persnr)).all()
    context={'pers':pers}
    return render(request, 'company/person.html', context)
like image 22
Marin Avatar answered Oct 03 '22 23:10

Marin