[Answer]-Django – how to config a dynamic url


Modify your url first to grab the id from the url:

(r'^summary/(?P<id>\d|[a-z]{24})/$', 'views.itemInfo', name="item_info"),

Put the same summary url in form action

action="{% url 'views.summary' %}"

In summary view check if request is a POST request then grab the id and redirect to the detail view else if request is GET or no id found in POST show summary view again:

def summary(request):
    if request.method == 'POST':
        id = request.POST.get('itemId')
        if id:
            return redirect(reverse('item_info', kwargs={'id': id}))
    return render_to_response(
        'summary.html', {}, context_instance=RequestContext(request))

The detail view should query the item by id and pass the item in context. You just name your template as item_detail.html and pass the object instance to show different items by using single template:

def itemInfo(request, id):
    item = MyItemModel.objects.get(id=id)
    return render_to_response(
        'item_detail.html', {'item': item}, context_instance=RequestContext(request))

Now play with item in item_detail.html.

Hope this helps you. Please take care of the imports your self.


You are mixing two important things: URLs and data passing methods (POST, GET, etc.). HTTP isn’t made to receive data such as what you planned to do using its URLs and frameworks (such as Django) will work against you if you persist going this way.

You should only have one page, namely /summary/. It should link to a view which checks if you have received an itemId in your POST data (if you keep your current HTML snippet). If not, only show the query form. Otherwise, add a div element which displays its data accordingly using template tags or filters. The built-in if template tag could be of use.

As an added bonus, your search form will still be available when an entry is entered and you will have less code to maintain.

I would recommend switching to the GET method, which is meant to do what you want. It will allow users that bookmark entries on your website to keep their reference to the item and not only the search form.

Leave a comment