0
votes

I want to render images that I uploaded from my Django admin in my template views. Since I need to upload multiple images at a time, I declared a separate model, ShowPhoto, with a foreign key attached to my Problem model:

models.py

class Problem(models.Model):
    slug = models.SlugField(null = False, unique = True, max_length = 255)
    topic = models.ForeignKey(Topic, on_delete = models.CASCADE)
    free = models.CharField(max_length = 1, choices = Free)

    #problem when introducing UUID field
    traceID = models.UUIDField(default=uuid.uuid4, editable = True)

    #use meta tags to optimize SEO
    metaTags = models.TextField(default = "")

    questionToProblem = models.TextField()

class ShowPhoto(models.Model):
    show = models.ForeignKey(Problem, on_delete = models.CASCADE, related_name = "photos")
    photo = models.ImageField()

    class Meta:
        verbose_name = 'Solution Image'
        verbose_name_plural = 'Solution Images'

Thus, in my admin.py, I also added:

class AdminImageWidget(AdminFileWidget):
    def render(self, name, value, attrs=None, renderer = None):
        output = []
        if value and getattr(value, "url", None):
            image_url = value.url
            file_name = str(value)
            output.append(u' <a href="%s" target="_blank"><img src = "%s" alt="%s" width="600" height="600"  style="object-fit: cover;"/></a> %s ' % \
                (image_url, image_url, file_name, _('')))
        output.append(super(AdminFileWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))

class ShowPhotoInline(admin.TabularInline):
    model = ShowPhoto
    formfield_overrides = {models.ImageField: {'widget': AdminImageWidget}}

@admin.register(Problem)
class ProblemModelAdmin(admin.ModelAdmin):
    form = ProblemForm
    list_display = ('questionToProblem', 'topic', 'free', 'traceID')
    search_fields = ('questionToProblem', 'traceID')
    readonly_fields = ('traceID',)
    fields = ('slug', 'traceID', 'topic', 'free', 'metaTags', 'questionToProblem', 'solutionToProblem', 'photos') #'solution_on_webpage', 'photos')
    inlines = [ShowPhotoInline]

    def save_related(self, request, form, formsets, change):
        super().save_related(request, form, formsets, change)
        form.save_photos(form.instance)

How would I write a view to render the images that I upload in my admin? When I try to write a QuerySet using the filter command like this: views.py

def displaySolution(request, topic_slug, problem_slug):
    try:
        solution = Problem.objects.get(topic__slug = topic_slug, slug = problem_slug)
        image = ShowPhoto.objects.filter(show = solution)
    except Exception as e:
        raise e
    return render(request, 'solution.html', {'solution' : solution, 'image' : image})

The QuerySet is called, but the rendering in the template is still blank. What do I need to do to fix it?

1

1 Answers

0
votes

Have you tried to specify the local path you want your images to be uploaded, like this:

class ShowPhoto(models.Model):
    show = models.ForeignKey(Problem, on_delete = models.CASCADE, related_name = "photos")
    photo = models.ImageField(upload_to = 'static/img')

Don't forget to run python manage.py makemigrations and python manage.py migrate after changing models.py