How can I transfer a JavaScript variable to a Django template before submitting the form?

Trying to fetch a selected approver and validate before submitting a form in Django has proven quite complex. I've made significant progress, but I'm stuck on figuring out how to "get" the translated ID in the Django template. I have the ID, but I can't make the final connection.

Here's the AJAX snippet:

 $("#avail").on("click", function(event) {
   var modalavail = document.getElementById("myModalavail");
   var markedCheckbox = document.querySelectorAll('input[type="checkbox"]:checked');
   event.preventDefault();
   $(window).unbind('beforeunload');
   $.ajax({
       method: 'get',
       headers: { "X-CSRFToken": token },
       url: "",
       processData: false,
       contentType: false,
       cache: false,
       enctype: 'multipart/form-data',
       success: function(resp) {
         modalavail.style.display = "block";
         for (var checkbox of markedCheckbox) {
         console.log(checkbox.value + ' ');
       }
       },
       error: function (request, status, error) {
         console.log(request.responseText);
         showAjaxFormErrors(JSON.parse(request.responseText));
         $('html, body').animate({ scrollTop: 0 }, 50);
         },
      });
   });

Here's the HTML snippet:

Check Availability

  <div class="table56">

    {% for entry in form.approvers %}

      <table class="table57">
        <thead>
          <tr>
            <th class="title156">Name</th>
            <th class="title118">Available?</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td class="title156">{{ entry.name }}</td>
            {% if not start_conflict or end_conflict or during_conflict %} 
            <td class="title117">Yes</td>
            {% else %}
            <td class="title117">No</td>
            {% endif %} 
          </tr>
        </tbody>
      </table>
    {% endfor %}
  </div>
  <input type="hidden" id="modal-approvers">
  <button type="button" class="button210" id="modalcloseavail">Close</button>
</div>

Here's the form snippet:

class DailyPlannerForm(forms.ModelForm):
    class Meta:
    model = NewDailyPlannerEvent
    exclude = [ 'created_by','summary']

def __init__(self, user, *args, **kwargs):
    start_time = kwargs.pop('start_time', None)
    User = get_user_model()
    super(DailyPlannerForm, self).__init__(*args, **kwargs)
    self.fields['approvers'] = forms.ModelMultipleChoiceField(
                            widget=forms.CheckboxSelectMultiple(),
                            queryset=User.objects.exclude(Q(is_active=False)).order_by('last_name','first_name'),required=False)

def clean(self):
    cleaned_data = super(DailyPlannerForm, self).clean()
    approvers = cleaned_data.get('approvers')

Here's the model snippet:

class DailyPlannerEvent(models.Model):

    STATUS_CHOICES = (
    ("AwaitingResponse","AwaitingResponse"),
    ("Cancelled","Cancelled"),
    ("Declined","Declined"),
    ("Delete","Delete"),
    ("Saved","Saved"),
    ("Scheduled","Scheduled"),
    ("Submitted","Submitted"),
)

STATUS_CHOICES1 = (
    ("Cancel","Cancel"),
)

STATUS_CHOICES3 = (
    ("True","True"),
    ("False","False"),
    ("N/A","N/A")
)

approver_by_department = models.ManyToManyField(Department,related_name="new_daily_planner_event_approver_by_department")
approvers = models.ManyToManyField(User)
created_by = models.ForeignKey(User,null=True,on_delete=models.CASCADE,related_name='new_daily_planner_event_created_by')
creation_date = models.DateTimeField(editable=False,null=True)
daily_planner_event_creation_date = models.DateTimeField(editable=False,null=True)
daily_planner_event_name = models.CharField(max_length=255,blank=True)
end_time = models.DateTimeField(null=True,blank=True)
last_update = models.DateTimeField(null=True)        
request_type = models.CharField(choices=REQUEST_TYPE,default="New Daily Planner Event Request",max_length=35)
start_time = models.DateTimeField(null=True,blank=True)
status = models.CharField(choices=STATUS_CHOICES,default="Submitted",max_length=20)
submitted = models.CharField(choices=STATUS_CHOICES3,default="False",null=True,blank=True,max_length=20)

And for the view snippet:

def get_context_data(self, **kwargs):
    context = super(DailyPlannerEventView, self).get_context_data(**kwargs)
    start_conflict = DailyPlannerEvent.objects.filter(
                     start_time__range=(dailyplannerevent.start_time,
                                        dailyplannerevent.end_time,approver=user))
    end_conflict = DailyPlannerEvent.objects.filter(
                   end_time__range=(dailyplannerevent.start_time,
                                    dailyplannerevent.end_time,approver=user))
    during_conflict = DailyPlannerEvent.objects.filter(
                      start_date__lte=dailyplannerevent.start_time, 
                      end_date__gte=dailyplannerevent.end_time,approver=user)
    context['start_conflict'] = start_conflict
    context['end_conflict'] = end_conflict
    context['during_conflict'] = during_conflict
    return context

Struggling with how to handle this line in the HTML:

{% for entry in form.approvers %}

Trying to get only the selected approvers in the form to display. Any insights are greatly appreciated. Thanks!

Answer №1

When searching for a solution, I came across the APIVIEW which was exactly what I needed. It allowed me to display form values before submitting the form.

My approach looked something like this:

class AvailabilityCheckView(views.APIView):

    def get(self, request):
        approvers = self.request.GET.getlist('approvers[]')
        start_time = self.request.GET.get('start_time')
        end_time = self.request.GET.get('end_time')

After that, I used Ajax to retrieve and process the values with Jquery to show them on the screen. I haven't yet figured out how to directly pass the values to the template, but I suspect there may be a way that I haven't discovered yet.

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

Tips for refreshing only a portion of a webpage using JavaScript/jQuery

I have two distinct navigational sections on my website. The left column has its own navigation menu, while the right column (main content area) contains a separate set of links: My goal is to click on a link in the left-hand sidebar (such as "Resume", "E ...

Showing hidden JavaScript elements in different parts of a webpage

Update: After making modifications to my JavaScript code, I am now encountering errors in the iPhone Debug Console. Disclaimer: As a newcomer to web development, I have limited expertise in JavaScript. Situation: My current project involves creating an e ...

Is there a way to use jQuery to adjust the text color once it has been clicked on?

I have been struggling to change the text color upon clicking on it without any success. Within my code, there are seven labels - one for the question, four for the answer options, one for the correct answer, and the last one for the explanation. The desi ...

Utilizing ng-repeat to iterate over a nested array

I need help figuring out how to properly loop through a JSON array and its ingredients/directions array using ng-repeat. The current method I have attempted is not working as expected. Any suggestions or advice would be greatly appreciated! Thank you. Con ...

Enhancing your JQuery Select2 plugin by incorporating a Checkbox feature

I am currently utilizing the jQuery select2 plugin to enable multiple selections. My goal is to incorporate a checkbox for each selectable option. Depending on whether the checkbox is checked or unchecked, the dropdown option should be selected accordingl ...

jquery code to count the number of children in an html table

I'm struggling to grasp the behavior of the jquery method children. I can successfully count the number of <p> elements within a <div> using the following code: var abc = $("div").children("p"); alert(abc.length); However, when I a ...

Interact with jQuery to trigger events upon clicking on a list item, excluding checkboxes within the list

I'm in the process of developing a straightforward web application. I have a dynamically generated list on one section: Subsequently, I set up an event that triggers when any element within the list is clicked: $(document).on('click', &apo ...

Using Express Validator is very easy and efficient once you understand its

Looking for a validator to catch errors and log them to the console Check out the code snippet below: const expressValidator = require('express-validator'); const { check, validationResult } = require('express-validator/check'); const ...

Issue with module exports not being defined in IE11/Edge

I am experiencing difficulties with an npm module that was updated to ES2015. My application is built in ES2015, bundled by browserify, and compiled with babelify. I am currently trying to upgrade a npm module called credit-card for validation, which has ...

Position a center pivot amidst a collection of 3D shapes within ThreeJS

I am currently working on creating a plugin prototype to allow customization of 3D objects using ThreeJS. You can view my progress so far here: If you've visited the link, you may have noticed that when hovering over the left or right arrow, the obje ...

In order to utilize the componentDidUpdate lifecycle method, I passed props to the Outlet component while nesting it

I am currently using react-router-v6 and encountering some issues with my configuration. I have implemented nested routing with layouts according to the following settings. App.js <BrowserRouter> <Routes> <Route exact pat ...

Publishing Your App on the Android Market with PhoneGap

Seeking a comprehensive PhoneGap tutorial that covers app publishing, especially struggling with successful app deployment. Currently experienced in HTML, CSS, and JavaScript. Any tips or advice would be greatly appreciated, thank you! I have a good gras ...

Utilizing Hyperlinks in jQuery DataTables Cell with Data Pulled from Mysql Table

I have a question that builds upon the one before it: How to display a hyperlink in a cell with jQuery DataTables There is also a Fiddle link provided My current query revolves around implementing hyperlinks when fetching data from a MySQL database table ...

Angular: Enhancing URL links

Recently, I discovered a function in my code that allows me to cycle through different pictures and change the URL accordingly. The initial URL is obtained using angular routes, where the "domain" parameter consists of the domain.id and the domain.category ...

A function in Jasmine for testing that returns a promise

I have implemented the following function: function getRepo(url) { var repos = {}; if (repos.hasOwnProperty(url)) { return repos[url]; } return $.get(url) .then(repoRetrieved) .fail(failureHandler); function ...

Display of Navigation Bar in Angular is Not Proper

Currently diving into the world of Angular, I've encountered an issue with a material menu that isn't displaying correctly. The expected outcome based on my code should resemble this image: https://i.stack.imgur.com/z70Aq.png This snippet showc ...

What manner must I understand this syntax?

After stumbling upon this code snippet online, I was left scratching my head: function cjsDetectionPlugin() { return { name: 'cjs-detection', moduleParsed({ id, meta: { commonjs: { isCommonJS } } }) { ...

Configuring Pagination Class for Django-Rest-Framework at Global Level in settings.py

I am currently working on implementing default pagination for all API calls: http://www.django-rest-framework.org/api-guide/pagination/#modifying-the-pagination-style My goal now is to ensure that my CustomPagination functions globally: class CustomPagi ...

The 'id' field was anticipating a numerical value, but received '<User: ben>'

I wrote a script to populate the database for my Django website, but after running the script and making migrations, I encountered an issue when trying to access objects created using the script within the Business model in the Django admin page of my site ...

Show the JSON data from the server in a table format

Is there a way to neatly display data received from an Ajax response within a table format? Below is the structure of the table: <table data-toggle="table" data-show-columns="true" data-search="true" data-select-item-name="toolbar1" id="menu_table"> ...