Implementing Django AJAX form submission: extracting a targeted model field from the form

In order to achieve my project goals, I am looking to implement a form submission using Ajax without any page refreshing. The Post model I am working with contains three fields: animal, image, and description.

Here is an image of the model

class Post(models.Model):
    # Animal choices

Here is the form.py code snippet

class PostForm(ModelForm):
    # Form Meta data

Here is a snapshot of the views page code

def homePage(request):
    # Post form handling logic

The issue I am facing seems to be with the JavaScript code used for form submission. While I can successfully submit the form, the 'data:{...}' section in my JavaScript code may be incorrect. I suspect an error on line 651 in the code snippet below.

View the AJAX JavaScript code snippet

 // JavaScript code snippet
        $(document).on('submit','#post-form',function(e){
            // Ajax form submission logic
        });

I am struggling to set the correct value in the JavaScript code snippet and my backend admin site shows empty posts in the database. I have attempted various approaches like $("form.model.animal").val() and $("form").val(animal) without success.

Check out my backend admin page with 'successful' submissions below for reference.

Admin Posts Page

Here is the template for the form field:

const postpopup = new mapboxgl.Popup({ offset: [0, -15] })
                    .setLngLat([lt, lg])
                    .setHTML(
                    `<h1>Yellowmap :) Post Forum</h1>
                        <div style="margin-left: 40px;">
                            <form id="post-form">
                            {% csrf_token %}
                            {{form}}
                            <input type="submit"/>
                            </form>
                            <p></p>
                        </div>`
                    )

Answer №1

Your code looks good overall, but there are some adjustments needed in your AJAX code and views.py file.

AJAX

    $(document).on('submit', '#post-form', function (e) {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: "{% url 'insert_form' %}",
            data:
                {
                    animal: $("#id_animal").val(),
                    image: $("#id_image").val(),
                    description: $("#id_description").val(),
                    csrfmiddlewaretoken: '{{ csrf_token }}',
                },
            success: function () {
                alert("success!")
            }
        })
    });

views.py

def homePage(request):
    form = PostForm()
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponse('')

    context = {'form': form}
    return render(request, '.html', context)

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

Is Django compatible with node anchors (&) and references (*) in YAML fixtures?

Is it possible to utilize node anchors and references in YAML fixtures with Django? Take a look at an example of how a YAML fixture with an anchor and reference might be structured: - model: auth.group pk: &somegroup 1 fields: name: "some gro ...

ObservableResolve(): Unleashing the power of RxJS5 for handling asynchronous data streams

Hey there! To dive deeper into RxJS, I thought of creating my own custom Rx operator. So here's a straightforward one that seems to be working smoothly: Rx.Observable.prototype.multiply = function (input) { const source = this; return Rx.O ...

Generate your own unique referral links today

Searching for ways to generate and monitor referral links like www.domain.com/?ref=switz What steps should I take to accomplish this? ...

Using JQuery to cycle a class with a timer

My list has the following structure <div id="slider"> <ul> <li class='active'> a </li> <li> b </li> <li> c </li> <li> d </li> <li> e </li> </u ...

Jquery script that utilizes the Steam WebAPI to return data

I'm encountering an issue with a script I found on github. I added value.appid myself, thinking it was logical, but I believe that data.response.games contains values for all my games. How can I either print or view what is defined? I would like to ...

React file viewer failing to display content via Firebase storage URLs

This code snippet is designed to display PDF files uploaded to Firebase storage using React. Here is a sample of the code: import ReactDOM from "react-dom"; import FileViewer from "react-file-viewer"; import "./styles.css"; ...

PHP Object-Oriented Programming Issue with PDO and AJAX

I am currently working with PHP OOP and PDO connection. I need assistance on how to call a function from a class using AJAX. For instance, let's say I want to call the printBooks function through AJAX. Class - Entity Book: class Book{ privat ...

Issue with datepicker initialization causing format not to work in Bootstrap

I am currently incorporating the angular-bootstrap datepicker module into my app and have run into a minor issue. I am using an input text field and a button to display the date in the following manner: <div class="row" id="datePicker"> <p cl ...

Integrate a Facebook Like-box within a customized jQuery modal window

I've been working on inserting the Facebook like-box code into my page and trying to display it within a jQuery modal dialog. Here's the code I'm using: <script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>< ...

Tips for using jQuery to slowly change a CSS property to "auto"

I've encountered a situation where I have an element styled with position:fixed, and bottom: auto;. When I apply the command .animate({bottom : '10%'});, it smoothly slides to the specified position. However, when I try to set it back to its ...

PHP not receiving values when making an AJAX POST request

My AJAX file below is where I pass all the values from my text boxes and post them to edu.php. In edu.php, I intend to update two tables - details and test. However, nothing seems to be updating in my database. When I checked the values with var_dump, the ...

What is the best way to wrap a call to XMLHttp Request within a $q promise?

I am trying to figure out how to wrap the following code in an AngularJS ui-router resolve section with a $q promise. The goal is to return success or fail based on whether the http request works. Should I encapsulate all of this inside a promise or just ...

get the data from a database table by specifying the ID and retrieve the corresponding column value

I am struggling to retrieve the value of a database column based on its ID. My goal is to show it in a <span> with the ID "#name_page" I pass the ID via POST using "$(this).attr("id")" This is my AJAX request $(document).on('click', &apo ...

Is it possible to trigger an event each time an Ajax request is made within AngularJS?

I am looking for a way to automatically display a spinner with a dark overlay every time a call is made to the backend. While I know I can manually implement this by triggering the spinner before each call, I prefer a solution that does not require addit ...

What is the best way to transfer the value of a slider from jQuery or JavaScript to a Python Flask application

Trying to implement a round slider that displays its value on the client-side webpage. Whenever the user adjusts the slider, the updated value needs to be sent to the server using Python Flask as the backend. I attempted to achieve this using jQuery and Aj ...

Styling elements using the nth-child selector in JavaScript

I am trying to apply a CSS class based on the combined height of the 2nd and 3rd child elements. For example, if the height of the 2nd child plus the height of the 3rd child equals a certain value, I want to add a specific class. Here is my JavaScript cod ...

Filtering Django ORM for the sum of multiple different related objects

I am in a situation where I have the following models: class Developer(models.Model): name = models.CharField(max_length=100) class Skill(models.Model): code = models.CharField(max_length=30) class Experience(models.Model): date_from = models ...

Step-by-step guide to creating a custom wrapper in React that modifies the props for a component

Exploring React components for the first time and seeking assistance. I am interested in dynamically wrapping one component inside another and modifying its props. For instance, considering the following component: If we want to pass the key3 from a wrapp ...

Send a file using ajax with the help of JavaScript and PHP

Currently, I am looking to implement a method for uploading files using Ajax and JavaScript/PHP without having the page refresh. My initial thought is to use Ajax to send the file using xmlhttp.send(file) and then retrieve it in the PHP script, but I' ...

Ancient queries carry the weight of time

Extremely ancient, very old, incredibly aged beyond belief ...