Vue.js not populating select option tags

I've encountered an issue with my profie.html code that is intended to display division dropdown values using vue.js v-for and {{ val.division_name }}. However, the dropdown is rendering blank values even though there are supposed to be values present.

             <select name="division_id" class="form-control form-select" id="division-id" aria-label="Default select example" v-model="formData.division_id" @change="onDivisionChange" required>
              <option value="0">Select Division</option>
              <option v-for="val in divisionListVue" :value="val.id">{{ val.division_name }}</option>
             </select>

https://i.sstatic.net/vKv3I.png

My custom-vue.js code:

const app = Vue.createApp({
  data() {
    return {
        divisionListVue: [], 
        calendarListVue: [], 
        formData: {
            division_id: 0, 
            division_name: '', 
            calendar_id: null, 
            calendar_name: '', 
        },
    };
},

methods: {

    showModal() {
        $("#modal1").modal('show'); 
    },
    
    fetchDivisionData() {
        fetch('/users/api/divisions/') 
        .then(response => response.json())
        .then(data => {
            console.log(data);
            this.divisionListVue = data;
            console.log(this.divisionListVue);
        })
        .catch(error => {
            console.error('Error fetching division data:', error);
        });
    },
    
    fetchCalendarData() {
        fetch('/users/api/calendars/') 
        .then(response => response.json())
        .then(data => {
            console.log(data);
            this.calendarListVue = data;
            console.log(this.calendarListVue);
        })
        .catch(error => {
            console.error('Error fetching calendar data:', error);
        });
    },
    
    onDivisionChange() {
        const selectedDivision = this.divisionListVue.find(item => item.id === this.formData.division_id);
        this.formData.division_name = selectedDivision ? selectedDivision.division_name : '';
        
      },
      
    onCalendarChange() {
        const selectedCalendar = this.calendarListVue.find(item => item.id === this.formData.calendar_id);
        this.formData.calendar_name = selectedCalendar ? selectedCalendar.calendar_name : '';
        
    },
   
},
mounted() {

    this.fetchDivisionData();
    this.fetchCalendarData();

 } 

});

app.mount('#app');

urls.py

urlpatterns = [
path('register/', views.register, name='register'),
path('login/', views.login_request, name='login'), 
path('profile/', views.profile, name='profile'),
path('api/divisions/', views.get_divisions, name='get_divisions'),
path('api/calendars/', views.get_calendars, name='get_calendars'),
  ]

views.py

# function to get the list of divisions
def get_divisions(request):
divisions = Division.objects.all()
data = [{'id': division.id, 'division_name': division.division_name} for division in divisions]
return JsonResponse(data, safe=False)


 # function to get the list of calendars
def get_calendars(request):
calendars = Calendar.objects.all()
data = [{'id': calendar.id, 'calendar_name': calendar.calendar_name} for calendar in calendars]
return JsonResponse(data, safe=False)

Data format returned by console.log(data)

https://i.sstatic.net/q4LFs.png

Data format returned by

console.log(this.divisionListVue);

The dropdown is displaying blank values despite having the necessary static files for vue to function correctly using

<script src="{% static 'js/vue.global.js' %}"></script>

Answer №1

The challenge I've encountered with integrating Vue.js into my Django project stems from the clash between Vue.js's double curly braces and Django's template syntax, both of which utilize the same syntax for variables.

Whenever I use {{ message }} in a Django template, it's recognized as a Django template variable rather than a Vue.js expression. To resolve this issue, I opted to modify Vue.js's template expression delimiters to something distinct from {{ }}. Vue.js offers a functionality known as "custom delimiters" that permits me to define alternative delimiters for Vue.js template expressions. Here's how I implemented the change in Vue.js delimiters:

const app = Vue.createApp({
delimiters: ['{[', ']}'], // Updated Vue.js delimiters to prevent conflicts with Django template tags
});
app.mount('#app');

Subsequently, I applied the custom delimiters for division and calendar as follows:

<option v-for="val in divisionListVue" :value="val.id">{[ val.division_name ]}</option>
<option v-for="val in calendarListVue" :value="val.id">{[ val.calendar_name ]}</option>
                     

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

Having trouble establishing a connection from regular JavaScript to a socket.io backend? Face the issue of connection closure before

As I attempt to link my client-side JavaScript with a backend websocket service utilizing socket.io, I encounter an issue. I am attempting to establish a connection to the socket.io server using the native WebSocket object: new WebSocket("wss://localhost ...

JavaScript autostop timer feature

An innovative concept is the solo cookie timer that holds off for one hour before resuming its function upon user interaction. No luck with Google. https://jsfiddle.net/m6vqyeu8/ Your input or assistance in creating your own version is greatly appreciate ...

TypeScript and Next.js failing to properly verify function parameters/arguments

I'm currently tackling a project involving typescript & next.js, and I've run into an issue where function argument types aren't being checked as expected. Below is a snippet of code that illustrates the problem. Despite my expectation ...

Automatically storing modified text from richtextbox into the database for safekeeping

I have developed a basic note-taking application using jquery and php. Currently, when the user clicks the save button, it sends an ajax request with all the data to update it in the mysql database. Everything is functioning correctly. However, I now want ...

Node.js Express.js Module for Asynchronous SqLite Operations

Currently, I am working on a task that involves making synchronous requests to a database and passing the data to Express. Here is the code snippet: app.get('/', (req, res) => { let db = new sqlite3.Database('./Problems.db'); ...

When applying the OWASP ESAPI encodeForHTMLAttribute method, I noticed that symbols are being rendered as their corresponding HTML entity numbers instead of the actual symbols

I recently started exploring OWASP ESAPI for preventing XSS and integrating the JavaScript version into my application. As per Rule #2 in the XSS prevention cheat sheet, it is recommended to "Attribute Escape" before inserting untrusted data into attribut ...

Store the token securely in your browser's localStorage and set up interceptors

Struggling with saving the token in localStorage and pushing it in interceptors to send it with all requests. Currently, passing user data and token from Symfony controller to frontend, but facing roadblocks in saving the token in localStorage and settin ...

Unable to establish SocketIO callback from client to server resulting in a null object instead

I'm encountering an unusual issue with SocketIO. On the server-side, I am using the emit() method like this: $s.sockets.emit(scope, {some: datas}, function(feedback) { console.log('received callback'); } ) ...

The Protractor Custom Locator is experiencing difficulty in finding the element

For our project, the automation team is incorporating a custom attribute called 'lid' to elements where unique identification is challenging. A new custom locator method has been developed to find elements using the 'lid' attribute: ...

Updating Element Value in Python Using JS and Selenium

Hello, everyone. I'm new to coding and seeking some help regarding a problem I encountered with using 2captcha for my Python web scraping automation. Upon running the script, I receive the captcha token from 2captcha as instructed in their API documen ...

Connecting onClick event to a dynamically created div using Dojo

While working with dojo 1.9.2, I encountered an issue when trying to add an onClick function to a dynamically created piece of HTML code like so: clickableDiv = "<div data-dojo-attach-point=\"testBtn\">Click Me!</div>"; self.racks.in ...

Why is Axios not being successfully registered as a global variable in this particular Vue application?

Recently, I have been delving into building a Single Page Application using Vue 3, TypeScript, and tapping into The Movie Database (TMDB) API. One of the hurdles I faced was managing Axios instances across multiple components. Initially, I imported Axios ...

Calculating the Distance Between Elements within a Flex Container Using JavaScript

I am looking to calculate the margin left and right for children of a flex item <div class="sec images" style="display:flex;justify-content:space-between"> <img src="images/en_mb-mega-01.png" alt=""> ...

What is the appropriate way to retrieve an array that has been stored in the this.state property?

https://i.stack.imgur.com/y9huN.jpgAs a newcomer to react, I have been exploring the react documentation on making Ajax calls. While the docs make it seem simple to retrieve JSON information and set it to a state variable, I've encountered some challe ...

Using jQuery to attach events and trigger them

Within my code, I have the following scenarios: $("#searchbar").trigger("onOptionsApplied"); And in another part of the code: $("#searchbar").bind("onOptionsApplied", function () { alert("fdafds"); }); Despite executing the bind() before the trigge ...

NextJS struggles to load EditorJS plugins

I am currently working on integrating EditorJS into my NextJS project. The editor is loading properly without any plugins, with only paragraph as a block option. However, I'm facing an issue when trying to add plugins using the tools prop which result ...

JSON with a null character

Despite spending an hour searching online, I feel a bit hesitant to ask this question. Can null characters (ascii null or \0) be used within JSON? I know they are not allowed within JSON strings, but my query is whether they can be included in the bod ...

Switch up the Thumbnail Image based on the selected category

While testing a shopping site I created, I encountered an issue with changing the banners at the top of the page based on the category the user is viewing. This site is hosted on a server on my localhost, not using wordpress by the way. <div class=" ...

Implement a mandatory parameter in the URL route using ui-router

My Angular routing configuration using ui-router is quite simple: $stateProvider .state("master", { abstract: true, url: "/{tenantName}" }) .state("master.home", { url: "", }) .state("master.login ...

Stop jQuery popups from wrapping text when resizing the browser window

Whenever a link is clicked, a jQuery popup appears. The popup functions properly in terms of opening and closing, but I would like to ensure that its position remains fixed when resizing the browser window to avoid any wrapping issues. Typically, I use a ...