在django模板中将子项排序为父项 [英] Sort children into parent in django template

查看:163
本文介绍了在django模板中将子项排序为父项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在学习Django(Python)的时候,我一直试图弄清楚这个问题。



我想将子对象排序到父对象中。具体来说,我想把城市分成各自的状态。然后,我希望城市以正确的状态显示在模板中。我正在寻找的是这样的:

$ p
---
--- City

---城市


编辑:我有一些工作。但是,这些城市正在重复自己的模板。我只需要每一个显示一次。我已经包含模板,看看有没有人可以帮我。



再次感谢。



模型.py

  class State(models.Model):
state_name = models.CharField(max_length = 20,default = ')
state_slug = models.SlugField()
state_image = models.ForeignKey(Image,null = True)
state_summary = models.TextField(null = True)

def __str __(self):
return self.state_slug
$ b $ class City(models.Model):
city_name = models.CharField(max_length = 55,default ='' )
city_slug = models.SlugField()
state_image = models.ForeignKey(Image,null = True)
school_image = models.ForeignKey(Image,null = True,related_name ='+')
state = models.ForeignKey(State,null = True)
def __str __(self):
return self.city_slug

views.py

 类CityInStateView(ListView):
模型=城市

context_object_name ='city_in_state_list'
$ b $ def get_context_data(self,** kwargs):
context = super(CityInStateView,self).get_context_data(** kwargs)
city = city.objects.all()
state = State.objects.get(state_slug = self.kwargs ['state_slug'])
context ['city_list'] = City.objects.filter(state = state).order_by('city_name')
返回上下文

urls.py



  urlpatterns = [
url(r'^ $',SchoolIndexView.as_view(),name ='school_index'),
url(r'^(?P ]

template.html

  {%block main_content%} 
< div class =row body>
< div class =main_content>
< div class =row>

< div class =medium-12 columns small-centered>
< div class =feature_wrapper>
{%load cloudinary%}
< header class =page_header>
< div class =row>
< div class =medium-12 columns>顶栏< / div>
< / div>
< / header>
< div class =search>
< div class =row>
< div class =medium-12 columns>搜索栏< / div>
< / div>
< / div>
{%if city_in_state_list%}
{city_in_state_list%中的城市%}
< section class =hero>
{%cloudinary city.state_image.image format =jpgcrop =fill%}
< p class =photo-caption> $ {{city.state_image.image_name}} {{city.state_image.image_author}} via {{city.state_image.image_source}} | {{city.state_image.image_license}}
< / p>
< / section>
< section class =summary>
< p> {{city.state.state_summary}}< / p>
< / section>
< div class =row>
< div class =medium-12 columns listicle>
< div class =demo_wrapper>
< div class =long_ad_box>
< img src =http://placehold.it/728x90>
< / div>
< / div>
< div class =state_name> $ {
< h2 class =headline>护理学校在{{city.state.state_name}}< / h2>
< / div>
{%if city_list%}
{%for city_list%}
< h2 style =text-align:left;> {{school.city_name}}< / H2>
< div class =school_image>
{%cloudinary city.school_image.image format =jpgcrop =fill%}
< / div>
{%endfor%}
{%endif%}
< / div>
< / div>
< / div>
< / div>
{%endfor%}
{%endif%}
< / div>
{%endblock%}

这一直踢我的屁股一个星期。请给我解释一下,就像我五岁那样。我很欣赏所有的帮助。
解决方案

我想你想使用一个DetailView代表状态,而不是一个列表的城市。这是因为你的URL代表一个状态的对象视图。



所以,你可以

 <$ c 



$ b $ get_context_data(self)$ b $ model $ = $ template $ ,** kwargs):
context = super(CityInStateView,self).get_context_data(** kwargs)
context ['state'] = self.object
context ['city_list'] = self.object.city_set.all()。order_by('city_name')
返回上下文

然后你的模板(简单的例子)就像这样简单:

 < h1> {{state.state_name}} < / H1> 
{city_list%中的城市%}
< p> {{city.city_name}}< / p>
{%endfor%}

对于使用DetailView的URL,不要使用 slug 作为字段名,你需要告诉DetailView state_slug是你的slu 。您可能需要在模型中添加 unique = True



希望您可以从这里

>

I have been trying to figure out this problem while learning Django (Python).

I would like to sort children objects into their parent. Specifically, I want to sort cities into their respective state. Then, I want the city to display in the template in its correct state. What I am looking for would like like this:

State
--- City
--- City
--- City

Edit: I've got it somewhat working. However, the cities are repeating themselves in the template. I only need each one to display once. I've included the template to see if anyone can help me with it.

Thanks again.

models.py

class State(models.Model):
    state_name = models.CharField(max_length=20, default='')
    state_slug = models.SlugField()
    state_image = models.ForeignKey(Image, null=True)
    state_summary = models.TextField(null=True)

    def __str__(self):
        return self.state_slug

class City(models.Model):
    city_name = models.CharField(max_length=55, default='')
    city_slug = models.SlugField()
    state_image = models.ForeignKey(Image, null=True)
    school_image = models.ForeignKey(Image, null=True, related_name='+')
    state = models.ForeignKey(State, null=True)
def __str__(self):
    return self.city_slug

views.py

class CityInStateView(ListView):
    model = City

    context_object_name = 'city_in_state_list'

    def get_context_data(self, **kwargs):
        context = super(CityInStateView, self).get_context_data(**kwargs)
        city = City.objects.all()
        state = State.objects.get(state_slug=self.kwargs['state_slug'])
        context['city_list'] = City.objects.filter(state=state).order_by('city_name')
        return context

urls.py

urlpatterns = [
    url(r'^$', SchoolIndexView.as_view(), name='school_index'),
    url(r'^(?P<state_slug>[\w-]+)/$', CityInStateView.as_view(), name='state_index'),
]

template.html

{% block main_content %}
<div class="row body">
    <div class="main_content">
        <div class="row">

            <div class="medium-12 columns small-centered">
                <div class="feature_wrapper">
                    {% load cloudinary %}
                    <header class="page_header">
                        <div class="row">
                            <div class="medium-12 columns">Top bar</div>
                        </div>
                    </header>
                    <div class="search">
                        <div class="row">
                            <div class="medium-12 columns">Search bar</div>
                        </div>
                    </div>
                    {% if city_in_state_list %}
                    {% for city in city_in_state_list %}
                    <section class="hero">
                        {% cloudinary city.state_image.image format="jpg" crop="fill" %}
                        <p class="photo-caption">
                            {{ city.state_image.image_name }} by {{ city.state_image.image_author }} via {{ city.state_image.image_source }} | {{ city.state_image.image_license }}
                        </p>
                    </section>
                    <section class="summary">
                        <p>{{ city.state.state_summary }}</p>
                    </section>
                    <div class="row">
                        <div class="medium-12 columns listicle">
                            <div class="demo_wrapper">
                                <div class="long_ad_box">
                                <img src="http://placehold.it/728x90">
                            </div>
                        </div>
                        <div class="state_name">
                            <h2 class="headline">Nursing Schools in {{ city.state.state_name }}</h2>
                        </div>
                        {% if city_list %}
                            {% for school in city_list %}
                            <h2 style="text-align: left";>{{ school.city_name }}</h2>
                            <div class="school_image">
                                {% cloudinary city.school_image.image format="jpg" crop="fill" %}
                            </div>
                            {% endfor %}
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
        {% endfor %}
    {% endif %}
</div>                                  
{% endblock %}

This has been kicking my butt for a week. Please explain it to me like I a m five. I appreciate all of your help in advance.

解决方案

I think you want to use a DetailView representing the state, rather that a list of cities. This because your URL represents a state's object view.

So, you can

class CityInStateView(generic.DetailView):
    model = State
    template_name = 'template.html'
    slug_field = 'state_slug'

    def get_context_data(self, **kwargs):
        context = super(CityInStateView, self).get_context_data(**kwargs)
        context['state'] = self.object
        context['city_list'] = self.object.city_set.all().order_by('city_name')
        return context

and then your template (simplified example) would be as simple as:

<h1>{{ state.state_name }}</h1>
{% for city in city_list %}
  <p>{{ city.city_name }}</p>
{% endfor %}

For the URL to work with DetailView, and because you did not use slug as the field name, you need to tell the DetailView that state_slug is your slug. You may want to add unique=True to your model.

Hope you can take it from here

这篇关于在django模板中将子项排序为父项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆