开发者

Django-- Retrieve specific object in templates

I'm trying to have the URL have a variable (say userid='variable') and that variable would be passed a开发者_开发技巧s an argument to retrieve a specific object with 'variable' as its name in some specific application's database. How would I do this?


Arie is right, the documentation for Django is excellent. Don't be intimidated, they make it very easy to learn.

From the Writing your first Django app, part 3 (https://docs.djangoproject.com/en/dev/intro/tutorial03/), the example shows you how to capture variables from the URL. In urls.py:

urlpatterns = patterns('',
    (r'^polls/$', 'polls.views.index'),
    (r'^polls/(?P<poll_id>\d+)/$', 'polls.views.detail'),
)

the line (r'^polls/(?P<poll_id>\d+)/$', 'polls.views.detail') says when the url is like mysite.com/polls/423, capture the \d+ (the 423) and send it to the detail view as variable named poll_id. If you change <poll_id> to <my_var>, the variable named my_var is passed to the view. In the view, the example has:

def detail(request, poll_id):
    return HttpResponse("You're looking at poll %s." % poll_id)

You in the body of this function, you could look up the poll Polls.objects.get(id=poll_id) and get all of the properties/methods of the Poll object.

ALTERNATIVELY, if you are looking to add URL variables (query string), like /polls/details?poll_id=423, then your urls.py entry would be:

    (r'^polls/details$', 'polls.views.detail'),

and your view:

def detail(request):
    poll_id = request.GET['poll_id']
    return HttpResponse("You're looking at poll %s." % poll_id)

In the body, you could still get details of the Poll object with Poll.objects.get(id=poll_id), but in this case you are creating the variable poll_id from the GET variable instead of allowing Django to parse from the url and pass it to the view.

I would suggest sticking with the first method.


Did you actually read the tutorial for Django?

To highlight just one sentence from Write your first view

Now lets add a few more views. These views are slightly different, because they take an argument (which, remember, is passed in from whatever was captured by the regular expression in the URLconf)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜