What is the best method for displaying my images using JsonResponse within Django's view?

I have a query regarding my colleague's code. The code is functioning properly and it displays some images that were previously uploaded via an input through a modal. However, I am facing an issue as I would like to showcase all 10 images in a detailed view. After attempting to modify the code, I am only able to display one image out of the 10 that were uploaded. How can I ensure that all 10 images are displayed? I am unfamiliar with how to work with the JSON structure that was utilized.

views.py


class detail_carro(DetailView):
    template_name = 'carros/carros-detail.html'
    queryset=Carro.objects.all()
    context_object_name = 'carros'


def create_carros_picture(request):

        if request.FILES['files']:
            file = request.FILES['files']
            fs = FileSystemStorage()  
            new_name = "picture"
            new_name = fs.get_valid_name(new_name)+".jpg"
            filename = fs.save(new_name, file)
            return JsonResponse({filename:file.name},safe=False)
        else:
            form=CarroForm()
            return render(request, "carros/carros-form-add.html",{'form':form})


def create_carros_warranty(request):
    if request.FILES['files']:
        file = request.FILES['files']
        fs = FileSystemStorage()  
        ext = file.name.split('.')[-1]
        new_name = "warranty"
        new_name = fs.get_valid_name(new_name) + '.' + ext
        filename = fs.save(new_name, file)
        return JsonResponse({filename: file.name}, safe=False)
    else:
        form = CarroForm()
        return render(request, "carros/carros-form-add.html", {'form': form})
 

carros-detail.html

{% if carros.new_name %}
<a data-id="{{carros.id}}" class="btn_view_gallery">
<img src="{% get_media_prefix %}{{carros.new_name}}" height="300">
</a>
{% endif %}

Answer №1

The DetailView is specifically designed to display a single model instance, such as the Carro in this scenario.

If you need to display multiple model instances, it's recommended to utilize the generic ListView.

For more information on how to use the ListView, visit: https://docs.djangoproject.com/en/4.0/ref/class-based-views/generic-display/#listview

In your views.py file:

class CarroListView(ListView):
    template_name = 'carros/carros-list.html'
    queryset=Carro.objects.all()
    context_object_name = 'carros'

Within carros/carros-list.html:

{% for carro in carros %}
<a data-id="{{carros.id}}" class="btn_view_gallery">
<img src="{% get_media_prefix %}{{carros.new_name}}" height="300">
</a>
{% endfor %}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The character count displayed in an ASP.NET text box may not match the character count of the text box on the

I've implemented a JavaScript function to show users the remaining character count on a page. However, when I validate the length server-side before inserting it into a database column, the count appears to be different. After researching online, it ...

Rendering on the server without using any client-side JavaScript

As I work on developing an application that can handle data submission through both ajax and traditional form requests, I am surprised by the lack of resources available online on this topic. It seems like we now generally assume client-side JS is readily ...

Manipulating and monitoring jQuery UI Carousel 1.0.2 through external controls

Currently, I have been utilizing jQuery UI Carousel (1.0.2) on my Drupal site. Everything is running smoothly, but I am interested in finding a way to incorporate external controls. Specifically, I want to add those small dots below the images that allow u ...

Exploring the Contrast between Application and Local State Management in Redux

When looking at various examples of Redux, actions like SOME_ASYNC_ACTION_ERROR and SOME_ASYNC_PENDING are commonly used to manipulate the global state. However, it is hard to imagine a scenario where it would be logical for a component to be initially ren ...

Using jQuery's .load() method to load a PHP file can result in an exponential increase in XHR finished loading time with each subsequent load

There seems to be an issue with my code using .load() to load a PHP page into a div whenever the navbar or link is clicked. After multiple clicks, I noticed that the "XHR finished loading" increases exponentially and it appears that the same PHP file is be ...

Exploring Django Crispy Forms and How They Handle Static Files

I have integrated Django Crispy Forms with Twitter-bootstrap by installing crispy forms as per the instructions on this link. However, I am struggling to locate the uni-form files that need to be included in my HTML code. Can anyone provide guidance on ho ...

Creating a Chrome extension with Angular 5: A comprehensive guide

Currently, I am in the process of developing a Chrome extension using Angular 5. Initially, I successfully created a basic Angular app with the help of Angular Material and it functioned perfectly as an Angular application (I used ng build for verification ...

Adjusting the size of objects in Three.js programaticallyAnswer: "Mod

Currently, I am utilizing the dat.gui library with three.js to allow users to interact with an object and adjust the dimensions of its mesh. While many online examples use scale to modify mesh dimensions like this: mesh.onChange(function(value){mesh.scale ...

Is it possible to utilize axios in Vue while utilizing CORS in the API?

I am encountering an issue with making a GET request to a CORS enabled corona virus API using axios and Vue. I have no control over their server, and my Vue app was created with vue-cli. Interestingly, I am able to make two requests from different APIs - ...

Initialize jQuery functions on newly generated element

My website has elements arranged like this: <ul> <li> <div class="tag_name">Tag Name</div> <div class="delete">X</div> </li> <li> <!-- and so forth... --> </l ...

Tips for running code extracted from a JSON payload

I have a JSON string that contains HTML and JavaScript code. I want to display this code on a page in my React app, but instead of just showing it as a string, I want the HTML and JavaScript to be executed as if it were hard coded. Currently, the code is ...

Validation of Ajax using the JQuery Form Validation Plugin

I have integrated the jQuery form validation plugin in my project, which can be found at When the form is invalid, my server responds with data in a name pair combination format like this: data: email:"Is invalid" name" "Is invalid" Can I ...

Surprising import quirks found in Python 3

Currently, I am utilizing the django-rules package in my project. To access this package, the following code is used: import rules In order for the files to be auto-discovered, this package necessitates the creation of a file named rules.py within each a ...

Transferring files to an Amazon S3 bucket through the Django admin

I have successfully configured my Django app to utilize S3 using the storages and boto packages. By running collectstatic, I managed to transfer my static assets to S3. However, I am facing an issue with storing image files uploaded from the Django Admin i ...

Node.js error: HTML audio file returns 404 on server but plays fine when accessed directly as an HTML file

I'm facing an issue with an HTML page that contains an autoplay tag for a song (the file is in mp3 format). When I open the page as a local file on my Mac, the song plays fine. However, when I try to run it using a node.js file with socket.io, the son ...

What is the best way to retrieve data from a numerical title in ReactJS?

Currently, I am retrieving information from an excel spreadsheet where the table header is in a numerical format (e.g. 2005-06) like this: https://i.sstatic.net/fLPh7.png Despite my efforts to access the data using objects, I keep encountering an error. ...

What is causing the error message "Uncaught TypeError: Cannot read property 'helpers' of undefined" to occur in my straight-forward Meteor application?

As I follow along with the tutorial here, I encounter an issue after replacing the default markup/code with the provided HTML and JavaScript. The error message "Uncaught TypeError: Cannot read property 'helpers' of undefined" appears. Below is t ...

How can I extract the last item from a custom ArrayList after parsing JSON data?

Currently experiencing an issue while parsing JSON data from a file located in the /assets folder. Setting up a custom ArrayList and attempting to add this data to a listview or spinner (using the same adapter) only displays the last item. Below is the cod ...

Simple method for counting unique values in React

Programming Language: JavaScript with React I am trying to calculate the number of unique "themes" in my data without counting duplicates. Data example: movies = [{"id" : 1, "name": "Ps: i love you", "theme": { ...

What is the best way to generate an AWS signature using Javascript?

I've been attempting to generate the AWS Mechanical Turk signature using Node.js, but I'm encountering difficulties. Currently, I am using the code snippet below, but it keeps throwing errors: CryptoJS.HmacSHA1(service + operation + timestamp, p ...