2017-10-02 1 views
0

내 목표는 페이지에 몇 가지 링크를 나열하는 것입니다 코드 줄 어떻게 더 나은 방법이 있는지 궁금 해서요 :이 부분은django 템플릿 가져 오기 URL 태그가 더 좋은 방법입니까?

<a href={% url ''|add:app_name|add:':'|add:model_name|add:post_fix %}> {{ model_name }} </a> 

: ''| 추가 APP_NAME을 | 추가가 ' : '| add : model_name | add : post_fix

- 그렇다면 내 생각에 결함은 무엇입니까, URL 이름입니까, 아니면 템플릿에서 너무 많이하고있는 것입니까? python 코드로 작성해야합니까? view.py 만약이 문제를 어떻게 해결할 수 있습니까?

a_template.html

{% for model_name in list_model_names%} 
    .... 
    <a href={% url ''|add:app_name|add:':'|add:model_name|add:post_fix %}> {{ model_name }} </a> 
    .... 
{% endfor %} 

from django.shortcuts import render_to_response 
from django.views import View 
from app.models import (Stone, Cloud) 
class ThisView(View): 
    template_name = 'app/a_template.html' 
    models = [Stone, Cloud] 
    model_names = [model._meta.model_name for model in models] 
    app_name = 'app' 
    post_fix = '_index' 

    dict_to_template = {'app_name': app_name, 
        'list_model_name': model_names, 
        'post_fix': post_fix} 

    def get(self, *args, **kwargs): 
     return render_to_response(self.template_name, self.dict_to_template) 

views.py

from django.conf.urls import url 

from . import views 

app_name = 'app' 
urlpatterns = [ 
url(r'^stone/$, view.....as_view(), name='stone_index'), 
url(r'^cloud/$', view.....as_view(), name='cloud_index'), 
] 
이 시간 내 주셔서 감사 url.py.

+1

'render_to_response'는 쓸모가 없습니다. 대신'render'를 사용하십시오. – Alasdair

답변

1

from django.urls import reverse . # Django 1.9+ 
# from django.core.urlresolvers import reverse # Django < 1.9 

model_names = [model._meta.model_name for model in models] 
app_name = 'app' 
post_fix = '_index' 
urls = [reverse('%s:%s%s' % (app_name, model, post_fix)) for model in model_names 

그런 다음 템플릿 상황에서 그들을 함께 모델의 이름과 URL을 압축하여 포함 템플릿의 URL을 반대로 정돈 될 것이다 :

models_and_urls = zip(model_names, urls) 
dict_to_template = {'models_and_urls: models_and_urls} 

할 수 있습니다 다음 루프를 템플릿의 모델 이름과 URL

{% for model_name, url in models_and_urls %} 
    .... 
    <a href="{{ url }}"> {{ model_name }} </a> 
    .... 
{% endfor %} 
관련 문제