简体   繁体   中英

Showing Details in Django Admin for Many to Many Relationship

I have a model where there are log class model and there is session class model. For each session there is several logs that can be recorded. So I created the following model:

class Log(models.Model):
    log_workout = models.CharField(max_length = 30, blank=True, null=True)
    log_exercise = models.CharField(max_length = 30, blank=True, null=True)
    log_order = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True)

class ActiveSession(models.Model):
    active = models.BooleanField(default=False)
    log = models.ManyToManyField(Log)
    date = models.DateTimeField(auto_now_add=True,blank=True, null=True)

In the admin I tried to use the inline so that I can see the details of each log in a session but it is only showing the full list and highlighting the added logs.

Here is the admin.py

class ActiveSessionInline(admin.TabularInline):
    model = ActiveSession.log.through

class LogAdmin(admin.ModelAdmin):
    model = Log
    inlines = [
        ActiveSessionInline,
    ]

My question: Can I instead of showing the added log in the below image to show the logs that is selected as if I am viewing them from LogAdmin even if it is inline

在此处输入图像描述

You can override the admin template and show the details.
You might even be able to add the javascript to do: if clicked remove from many-to-many field

But:

  • You won't be able to edit the Logs without extra stuff- like a popup form + js + View to submit to
  • original.log.all only contains things that are currently selected.. You'd almost have to either:
    • get into the form from fieldset and loop through the field's options to show all
    • or you could somehow pack extra data into the ModelAdmin
admin.py
class LogAdmin(admin.ModelAdmin):
    model = Log
    inlines = [
        ActiveSessionInline,
    ]

    # override template
    change_form_template = 'admin/logadmin_change.html'
logadmin_change.html
{% extends "admin/change_form.html" %}

{% block field_sets %}

   
  <!-- Original Field Loop -->
  {% for fieldset in adminform %}
    {% include "admin/includes/fieldset.html" %}
  {% endfor %}

  <!-- Custom Loop - 'original' is current Model being changed -->
  {% for i in original.log.all %}
    <div class="selectedLogs" pk="{{i.pk}}">
      {{i}} (make better looking tho)
    </div>
  {% endfor %}

{% endblock %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM