Note that Django knowledge points (a)

本篇 Overview

  Django Admin backstage show-many fields (how)

  Django template display field-many (how)

models code background

1 class Tag(models.Model):
2         name = models.CharField(max_length=20, verbose_name="名称")
3 
4 class work(models.Model):
5         Tag = models.ManyToManyField(Tag, verbose_name="标签")

 

A, Django Admin many-field background display

  In admin.py file

. 1  @ admin.register (Work)
 2  class workAdmin (admin.ModelAdmin):
 . 3      '' ' show Tags ' '' 
. 4      DEF show_tags (Self, obj):
 . 5          return [tag.name for Tag in obj.Tag.all ( )]
 6           # here use the Python stack conduction 
. 7      show_tags.short_description = " tag "   # set header 
. 8      list_display = [ " show_tags " ]

 

Two, Django template display field-many

   First with a view views.py file

1 class IndexView(View):
2     def get(self, request):
3         works = work.objects.all()[:2]
4 
5         context = {
6             'works': works,
7         }
8         return render(request, 'index.html', context)

  Then, (urls.py configuration is not to say, how to get directly into the template)

. 1  {%}% for Works Work in
 2        {%}% for Tag in work.Tag.all
 . 3               {i.e., corresponding to the below # ad tag} #
 . 4                     {} {} tag.name  
 . 5         {%} endfor%
 . 6 { % endfor%}    

 

Guess you like

Origin www.cnblogs.com/xmdykf/p/11403000.html