Iterating over model attributes when creating a template in Django

I am using Django in the Google App Engine. If i have a class

class Person():
    first_name = StringProperty()
    last_name = StringProperty()

and I have an instance where Person.first_name = Bob and Person.last_name = Vance, can I create a template that iterates over the Person attributes to create:

<tr>
<td>First</td>
<td>Bob</td>
</tr>
<tr>
<td>Last</td>
<td>Vance</td>
</tr>

Perhaps more concisely, is there a model.as_table () method that will print the attributes of my instance, Bob Vance?

+3
source share
4 answers

In the template, you cannot access the attributes or functions of __underscored__. Instead, you create a function in your model / class:

class Person(models.Model):
  first_name = models.CharField(max_length=256)
  last_name = models.CharField(max_length=256)

  def attrs(self):
     for attr, value in self.__dict__.iteritems():
        yield attr, value

 def sorted_attrs(self):
     # Silly example of sorting
     return [(key, self.__dict__[key]) for key in sorted(self.__dict__)]

In the template, this is simple:

 <tr>
 {% for name, value in person.attrs %}
   <td>{{name}}</td> 
   <td>{{value}}</td>
 {% endfor %}
 </tr>

"first_name" "First", . , mixin, .. , , :

{% for person in persons %}
 <tr>
 {% for name, value in person.attrs %}
   <td>{{name}}</td> 
   <td>{{value}}</td>
 {% endfor %}
 </tr>
{% endfor %}
+8

:

for attr, value in a.__dict__.iteritems():

for attr, value in self.__dict__.iteritems():
+2

, Dev (http://groups.google.com/group/django-developers/browse_thread/thread/44cd834438cfda77/557f53697658ab04?lnk=gst&q=template+model#557f53697658ab04):

add:

from django.forms.models import model_to_dict

def show(request, object_id):
    object = FooForm(data=model_to_dict(Foo.objects.get(pk=object_id)))
    return render_to_response('foo/foo_detail.html', {'object': object})

add:

{% for field in object %}
    <li><b>{{ field.label }}:</b> {{ field.data }}</li>
{% endfor %}
+2
def model_to_dict(instance, fields=None, exclude=None):
    """
    Returns a dict containing the data in the ``instance`` where:
    data = {'lable': 'verbose_name', 'name':name, 'value':value,}
    Verbose_name is capitalized, order of fields is respected.

    ``fields`` is an optional list of field names. If provided, only the named
    fields will be included in the returned dict.

    ``exclude`` is an optional list of field names. If provided, the named
    fields will be excluded from the returned dict, even if they are listed in
    the ``fields`` argument.

    """

    data = []
    if instance:
        opts = instance._meta
        for f in opts.fields:
            if not f.editable:
                continue
            if fields and not f.name in fields:
                continue
            if exclude and f.name in exclude:
                continue

            value = f.value_from_object(instance)

            # load the display name of choice fields
            get_choice = 'get_'+f.name+'_display'
            if hasattr(instance, get_choice):
                value = getattr(instance, get_choice)()

            # only display fields with values and skip the reset
            if value:
                if fields:
                    data.insert(fields.index(f.name), {'lable': f.verbose_name.capitalize(), 'name':f.name, 'value':value,})
                else:
                    data.append({'lable': f.verbose_name.capitalize(), 'name':f.name, 'value':value,})
    return data

TODO

  • , @property
0

Source: https://habr.com/ru/post/1713358/


All Articles