Reputation: 2990
I have two page which display item summary and item detail info respectively. the url.py like this:
(r'^summary/$', 'views.summary'),
(r'^summary_\d|[a-z]{24}$', 'views.itemInfo'),
The summary.html
can query a item by id then jump to summary_{{itemId}}.html
to display the item detail information. The itemId is mongodb ObjectId, then I use regex '\d|[a-z]{24}
'.
In summary.html
template I write:
<form action="???" method="post">
query Item by id:
<input type="text" name="itemId" value="" /><br />
<input type="submit" value="query" />
</form>
My problems:
What should I write in '???' place, the url to go is dynamic formed.
How I name the template file(summary_{{itemId}}.html
which used to displaying item info?
Upvotes: 0
Views: 1142
Reputation: 39689
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.
Upvotes: 1
Reputation: 9983
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.
Upvotes: 0