Reputation: 1599
Im newbie use python and django, I have problem in django admin site.
My plan is to give a different url to any existing data from many to many relationships that appear on the admin site table. When click data siswa will lead to the edit page.
# model.py
class WaliSiswa(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
title = models.CharField(max_length=11, choices=TITLE)
nama_lengkap = models.CharField(max_length=125)
jenis_kelamin = models.CharField(max_length=1, choices=GENDER_CHOICES)
relations = models.CharField(max_length=50, choices=RELATIONS)
tempat_lahir = models.CharField(max_length=255)
tanggal_lahir = models.DateField()
alamat_ktp = models.CharField(max_length=500)
alamat_tinggal_saat_ini = models.CharField(max_length=500)
profesi = models.CharField(max_length=225)
nomer_telepon = models.CharField(max_length=25)
nomer_seluler = models.CharField(max_length=25)
email = models.CharField(max_length=125)
siswa = models.ManyToManyField(Siswa)
# admin.py
class WaliSiswaAdmin(admin.ModelAdmin):
list_display = ('getTitleNamaLengkap', 'relations', 'getSiswa', )
def getSiswa(self, obj):
return ', '.join([d.nama_lengkap for d in obj.siswa.all()])
getSiswa.short_description = 'Siswa'
Like the picture above, I managed to display the data but confused to add its url. So I am very grateful for you who can provide the best solution.
Upvotes: 0
Views: 100
Reputation: 12086
Django docs have you covered about how you can reverse
admin urls.
Also, we'll need the pretty handy format_html_join
method.
# admin.py
from django.core.urlresolvers import reverse # django 1.9-
from django.urls import reverse # django 1.10+
from django.utils.html import format_html_join
class WaliSiswaAdmin(admin.ModelAdmin):
list_display = ('getTitleNamaLengkap', 'relations', 'getSiswa', )
def getSiswa(self, obj):
# Signature: format_html_join(sep, format_string, args_generator)
return format_html_join(
', ',
'<a href="{}">{}</a>',
[(reverse('admin:<your_app_name>_siswa_change', args=(d.id,)), d.nama_lengkap) for d in obj.siswa.all()]
)
getSiswa.short_description = 'Siswa'
If you're using Python 3.6 then use f-strings (!):
from django.core.urlresolvers import reverse # django 1.9-
from django.urls import reverse # django 1.10+
from django.utils.html import mark_safe
class WaliSiswaAdmin(admin.ModelAdmin):
list_display = ('getTitleNamaLengkap', 'relations', 'getSiswa', )
def getSiswa(self, obj):
return mark_safe(
', '.join([f'<a href="{reverse("admin:<your_app_name>_siswa_change", args=(d.id,))}">{d.nama_lengkap}</a>' for d in obj.siswa.all()])
)
getSiswa.short_description = 'Siswa'
Upvotes: 1