django ajax request returning a 403 error

While attempting to compile project https://github.com/kannan4k/django-carpool, I encountered an error during an ajax call. The error message displayed was: "Failed to load resource: the server responded with a status of 400 (BAD REQUEST)."

I suspect that this issue is related to the ajax post request and CSRF tokens based on my settings. I have disabled the

"django.middleware.csrf.CsrfViewMiddleware"
and have a button in the new_trip page that triggers an ajax request.

Below is a snippet from my view:

@login_required
def save_journey(request):

    if request.is_ajax() and request.method == "POST":
        try:
            res = json.loads(request.body)
            cords = res['cords']
            cords = [[x['d'], x['e']] for x in cords]
            distance = res['distance']
            start_place = res['start']
            end_place = res['end']
            clusters = clusterize_latlngs(cords, distance)
            time = datetime.datetime.strptime(res['time'], "%m/%d/%Y %H:%M")
            Trip.objects.create(user=request.user, time=time, cluster=json.dumps(clusters), travel_distance=distance,
                                start_place=start_place, end_place=end_place)

            return HttpResponse()
        except:
            return HttpResponseBadRequest()
    else:
        return HttpResponseNotAllowed(['POST'])

Additionally, there is an Ajax call implemented in home.js file:

function postData() {
    // Code implementation here...
}

The code seems to be unable to reach the /save_journey/ URL despite trying various solutions found on Stack Overflow. If anyone has insights on why this may be happening, any help would be greatly appreciated.

Answer №1

It is highly advised to never disable the csrftoken unless you are fully aware of what you are doing. This token plays a crucial role in the security measures implemented by Django.

Let's take a look at how Ajax can be utilized with Django along with the csrftoken:

You can employ Ajax Post to dispatch JSON to Django and then manage the parameters as a dict(). Here's an illustration:

In a web browser (using JQuery/JavaScript):

function newModule() {

    var my_data = $("#my_element").val(); // Input your desired value.

    $.ajax({
        url: "{% url 'modules' %}",       // Handler defined in Django URLs.
        type: "POST",                     // Method type.
        dataType: "json",                 // Data format as JSON (Default).
        data: {
            path: my_data,                // Key in dictionary (JSON).
            csrfmiddlewaretoken:
                     '{{ csrf_token }}'   // Unique key for CSRF protection.
        },

        success: function (json) {

            // Actions to perform on successful response.

        },

        error: function (xhr, errmsg, err) {

            // Actions to take upon failure.

        }

    });

In the server-side engine (using Python):

def handle(request):

    # Check for POST request containing the specified key.
    if request.method == 'POST' and 'my_data' in request.POST.keys():

        # Retrieve the value associated with the key.
        my_data = request.POST['my_data']

    # Additional logic can be added here.

We hope this explanation proves useful.

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

Gathering data from a string delimited by two distinct characters, including the final value

For instance: x=0, y=0, width=1920, height=1080, width_mm=531, height_mm=299, name='\\\\\\\\.\\\\DISPLAY4', is_primary=True I am interested in extracting all the values after the "=" si ...

Updating the parent's data by modifying data in the child component in VueJS

When I use multiple components together for reusability, the main component performs an AJAX call to retrieve data. This data is then passed down through different components in a chain of events. <input-clone endpoint="/api/website/{{ $website->id ...

Ways to reach state / methods outside of a React component

Implementing the strategy design pattern to dynamically change how mouse events are handled in a react component is my current task. Here's what my component looks like: class PathfindingVisualizer extends React.Component { constructor(props) { ...

Extract ID for Bootstrap modal display

In my project, I am using a bootstrap modal that displays various strings. The challenge I am facing involves a loop of cards, each with a distinct 'id'. When triggering the modal, I want to show the corresponding id inside the modal itself, whic ...

Getting the value of a variable within the scope of AngularJS can be achieved by utilizing

I have an ng-repeat directive in my code that displays slides. Here is a snippet of the data: slides = [{ src: "/sikiosk/slidedata/Global/NA/USNS/Cafeteria/5000_24.jpg", interval: 5000 }, { src: "/sikiosk/slidedata/Global/NA/USNS/Cafeteria/5000_login-regi ...

Creating a stunning art exhibition using React Native

Currently, I am in the process of creating a gallery component that utilizes both the scrollview and image APIs. I'm curious about how the scrollview manages its child components when it scrolls down. Does it unmount the parts that are not currently ...

Can you explain how to invoke a class with express().use function?

Currently, I am delving into learning Node JS with TypeScript but have hit a roadblock with a particular issue. In my app.ts file, I have initialized the express and attempted to call the router class inside the app.use() method, only to encounter an error ...

The transitioning period caused the gooey effect to become distorted

I'm currently working on creating a radio button with a gooey effect. The transition looks great, but once it's complete, the colors don't blend well and the edges glow in an odd way. I've been searching for the root of the issue, but ...

Please note: With React 18, the use of ReactDOM.render is no longer supported. Instead, we recommend using create

I encountered an issue while attempting to link my React application with a MongoDB database. Here is the code snippet where the problem occurred: //index.js ReactDOM.render( <React.StrictMode> <BrowserRouter> <App /> &l ...

JavaScript - continuously update the image marked as "active"

I have a collection of 4 pictures that I want to rotate through in my web application. Each picture should have the "active" class applied to it, similar to when you hover over an image. .active, .pic:hover{ position: absolute; border: 1px solid ...

retrieving a colorbar tick from matplotlib that falls beyond the dataset boundaries, intended for use with the

I am attempting to utilize a colorbar to label discrete, coded values shown using imshow. By utilizing the boundaries and values keywords, I am able to achieve the desired colorbar where the maximum value is effectively 1 greater than the maximum data valu ...

Guide on how to trigger an alert and confirmation pop-up upon detecting a click on the browser's back

I'm currently developing an exam application using php and jquery. The application includes several pages for creating exams: Create.php (for entering exam details) QandA.php (to add questions and answers) Marks.php (for setting up marks) Penalty.ph ...

When attempting to execute a query in Node using oracledb, an error with the code 'npm ERR! errno 3221225477' occurred

Encountered the following error message in the command line: npm ERR! code ELIFECYCLE npm ERR! errno 3221225477 npm ERR! [email protected] start: `node ./bin/www` npm ERR! Exit status 3221225477 npm ERR! npm ERR! Failed at the [email protected] start sc ...

Retrieve the page dimensions from a Material UI component `<DataGrid autoPageSize/>`

When utilizing <DataGrid autoPageSize/>, as outlined in the documentation, you can have a Material UI table that adjusts its page size based on the browser height. However, if you are fetching data from the server progressively, it becomes essential ...

data.failure defined

Currently working on a submission form that utilizes ajax, json, and PHP. The data is being properly handled with the database. However, when I use the script, alert(data.success) returns as undefined. Yet when I alert(data), it shows that what I need is p ...

Connecting JavaScript and jQuery scripts

Help needed! I am a beginner in the world of jQuery and JS. Unfortunately, my JS/jQuery code is not running and I can't figure out why. Can someone please take a look at my HTML and guide me on what might be causing the issue? Do I need to add some ad ...

Implementing Material-UI Autocomplete: How to Include a Starting Value for the startAdornment

I am using autocomplete with multiple selection permission. https://codesandbox.io/s/bold-jackson-dkjmb?file=/src/App.js In the provided example, there are 3 options for cities. How can I manually insert a value in TextField that is automatically selected ...

Balancing heights with jQuery

Is there a way to set the height of an h3 element based on the tallest version of its siblings, but only for certain elements? I have a list where CSS organizes items into rows of 3. The last li element in each row has the class "endRow". I want to find t ...

Troubleshooting Proxy.php issues in conjunction with AJAX Solr

Attempting to access a Solr 4.5.0 instance located on a private server, http://12.34.56.789:8983/ The application resides at this web server address, http://www.mywebapp.com To facilitate accessing the JSON object within the Solr instance, I decided to ...

Grab a parameter from the URL and insert it into an element before smoothly scrolling down to that

On a button, I have a URL that looks like this: www.mywebsite.com/infopage?scrollTo=section-header&#tab3 After clicking the button, it takes me to the URL above and opens up the tab labeled tab3, just as expected. However, I would like it to direct m ...