Home > Software design >  show related fields in django admin panel
show related fields in django admin panel

Time:10-29

I have 3 django models. Requirement Model has its own fields. RequirementImage and RequirementDOc models have Requirement as foreign key in them which are used for multiple image and multiple document upload. In admin ,I want to show the Requirement along with the images and documents related to requirement. How can i show it in admin panel. i want to show a view where i can list all fields of Requirement and RequirementImages and RequirementDocs together. Below is the exact code of models.

class Requirement(models.Model):
    name = models.CharField(max_length=100)
    description = models.CharField(max_length = 5000) 
    mobile = models.CharField(max_length=15, null=True, blank=True)
    email = models.EmailField(null=True, blank=True) 
    city = models.CharField(max_length=100)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
class RequirementImage(models.Model):
    requirement = models.ForeignKey('Requirement', on_delete=models.CASCADE)
    image = models.ImageField(null=True, blank=True, validators=[
            FileMimeValidator()
        ], upload_to=settings.MEDIA_RELATIVE_ROOT   "requirements/images")

class RequirementDoc(models.Model):
    requirement = models.ForeignKey('Requirement', on_delete=models.CASCADE)
    requirement_file = models.FileField(null=True, blank=True, upload_to=settings.MEDIA_RELATIVE_ROOT   "requirements/docs")

Python version is 3.7.12 and django version is 3.2.14

CodePudding user response:

in models.py

from django.utils.safestring import mark_safe

class RequirementImage(models.Model):
requirement = models.ForeignKey('Requirement', on_delete=models.CASCADE)
image = models.ImageField(null=True, blank=True, validators=[
        FileMimeValidator()
    ], upload_to=settings.MEDIA_RELATIVE_ROOT   "requirements/images")
    def photo_tag(self):
        return mark_safe('<a href="/your_path/{0}"><img src="/your_path/{0}"></a>'.format(self.image))
photo_tag.short_description = 'Photo of prescription'
photo_tag.allow_tags = True

and when you want to use it in admin

list_display = ('get_photo')
def get_photo(self, obj):
    return obj.photo.photo_tag()

get_photo.short_description = 'Photo of prescription'

CodePudding user response:

This is the right answer.we need to use TabularInline.

class RequirementImageInline(admin.TabularInline):
    model = RequirementImage
    fields = ['image']
    extra = 1

class RequirementDocInline(admin.TabularInline):
    model = RequirementDoc
    fields = ['requirement_file']
    extra = 1

class RequirementAdmin(admin.ModelAdmin):
    inlines = [RequirementImageInline,RequirementDocInline]

Reference: https://stackoverflow.com/a/74233744/1388835

  • Related