Putting links in list_detail.object_list to list_d

2019-06-13 20:19发布

I've started using Django and am going right to generic views. Great architecture! Well, the documents are great, but for the absolute beginner it is a bit like unix docs, where they make the most sense when you already know what you're doing. I've looked about and cannot find this specifically, which is, how do you set up an object_list template so that you can click on an entry in the rendered screen and get the object_detail?

The following is working. The reason I'm asking is to see if I am taking a reasonable route or is there some better, more Djangoish way to do this?

I've got a model which has a unicode defined so that I can identify my database entries in a human readable form. I want to click on a link in the object_list generated page to get to the object_detail page. I understand that a good way to do this is to create a system where the url for the detail looks like http://www.example.com/xxx/5/ which would call up the detail page for row 5 in the database. So, I just came up with the following, and my question is am I on the right track?

I made a template page for the list view that contains the following:

<ul>
{% for aninpatient in object_list %}
<li><a href='/inpatient-detail/{{ aninpatient.id }}/'>{{ aninpatient }}</a></li>
{% endfor %}
</ul>

Here, object_list comes from the list_detail.object_list generic view. The for loop steps through the object list object_list. In each line I create an anchor in html that references the desired href, "/inpatient-detail/nn/", where nn is the id field of each of the rows in the database table. The displayed link is the unicode string which is therefore a clickable link. I've set up templates and this works just fine.

So, am I going in the right direction? It looks like it will be straightforward to extend this to be able to put edit and delete links in the template as well.

Is there a generic view that takes advantage of the model to create the detail page? I used ModelForm helper from django.forms to make the form object, which was great for creating the input form (with automatic validation! wow that was cool!), so is there something like that for creating the detail view page?

Steve

1条回答
闹够了就滚
2楼-- · 2019-06-13 20:52

If you're on django < 1.3 then what you are doing is basically perfect. Those generic views are quite good for quickly creating pages. If you're on django 1.3 you'll want to use the class based generic views. Once you get a handle on those they are are crazy good.

Only note I have is that you should use {% url %} tags in your templates instead of hardcoding urls. In your urls.conf file(s) define named urls like:

url('inpatient-detail/(?P<inpatient_id>\d+)/$', 'your_view', name='inpatient_detail')

and in your template (for django < 1.3):

<a href="{% url inpatient_detail inpatient_id=aninpatient.id %}">...</a>

In 1.3 a new url tag is available that improves life even more.

查看更多
登录 后发表回答