Executing a custom Django view class method at a single URL path

I'm a newcomer to the world of Django and I am interested in managing my database using custom methods within the views file. For instance, I have written this code that I would like to execute with JavaScript:

Js:

$.ajax({
        type: 'POST',
        url: '/ClassManager/',
        data: {
            data: data,
            csrfmiddlewaretoken: csrftoken,
        },
        success: function() {
            alert("IT WORKED")
        },
        error: function() {
            alert('error');
        }
    })

views.py

def expfunc():
    if request.method == 'POST':
            user = User.objects.get(pk=1)
            addlst = List(content = "list content", creator = user)
            addlst.save()

urls.py

urlpatterns = [
    path('ClassManager/', views.expfunc),
]

The issue I encounter is that for each new function I create in the views.py file, I must add another line in the urls.py file.

My question is - is there a way to create a class with all the custom methods and access them through one URL with different data?

For example:

Js:

$.ajax({
        type: 'POST',
        url: '/ClassManager/functionone()',
        data: {
            data: data
            csrfmiddlewaretoken: csrftoken,
        },
        success: function() {
            alert("IT WORKED")
        },
        error: function() {
            alert('error');
        }
    })

views.py

class DatabaseManager():
    def functionone(): # add new list
        if request.method == 'POST':
                user = User.objects.get(pk=1)
                addlst = List(content = "list content", creator = user)
                addlst.save()
    def functwo(): # update username
        if request.method == 'POST':
                user = User.objects.get(pk=1)
                user.id = 9
                user.save()
    def functhree(): # update list content
        if request.method == 'POST':
                user = User.objects.get(pk=1)
                mylist = List.objects.get(pk=1)
                mylist.content = "updated list content"
                mylist.save()

urls.py

urlpatterns = [
    path('ClassManager/functionone()', views.DatabaseManager.functionone),
]

Coming from an ASP.NET background where I had classes with functions to manage databases, can I implement a similar structure in Django?

Thanks in advance!

Answer №1

Utilizing Class Based Views in Django allows you to structure your views as Python objects rather than traditional functions. However, it's important to note that calling a class function using Ajax is not supported.

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

Why am I encountering the "500 (Internal Server Error) when utilizing Wordpress with Ajax and trying to make a POST request to http://54.xx.xx.xx/wp-admin/admin-ajax.php?

Today marks my first attempt at utilizing ajax on WP. As I dive into creating a simple contact form, an error keeps cropping up whenever I hit submit: Displayed in the console: POST http://54.xxx.xx.xx/wp-admin/admin-ajax.php 500 (Internal Server Error) ...

Is it possible to quickly sync API data with a CSV file for updates?

My unique code allows retrieving Amazon product prices with the ASIN (Amazon Standard Identification Number). Here is the code snippet for reference. <?php class AmazonAPI { // Code implementation details here } ?> To display the price, use ...

Creating custom CSS for Styled Components in ReactJS

I'm struggling with CSS in React using styled components. Below is the code snippet I am working with: import React from 'react'; import { Navbar, Container, Row, Col } from 'reactstrap'; import styled from 'styled-components& ...

Finding clarity amidst the chaos of require and export in Express.js (Node.js)

Is there a way to make my socket.io connection modular so that it can run once and be accessible anywhere? How can I export it? var server = require("http").Server(express); var io = require("socket.io")(server); server.listen(5000); io.on('connect ...

Should I release an Aurelia component on NPM?

Our team has developed a compact Aurelia application and now we are looking to seamlessly incorporate it into a larger codebase. One possible scenario is distributing the Aurelia app on NPM to allow other projects to easily integrate our code. What steps ...

Solving Problems with Inline Tables using Angular, Express, and Mongoose's PUT Method

For the past few days, I've been struggling to figure out why my PUT request in my angular/node train schedule application isn't functioning properly. Everything else - GET, POST, DELETE - is working fine, and I can successfully update using Post ...

Having trouble with submitting a Vue.js form when toggling the visibility of a bootstrap panel?

There are three bootstrap panels that are displayed depending on the selection made in the select element: <div class="panel panel-default"> <Select/> </div> <div class="panel panel-default" v-if="fileMode == 0"></div> <d ...

What techniques can I use to streamline the following?

var cleanWord = word .split(/[^a-z0-9\s.\|]/gi) .join("") .replace(/([~@#$%^&*()_+=`{}\[\]\\:;<>\/ ])+/g, ""); I suspect that I am redundantly using the join function twice here. Is there a way to ...

Active positioning within a parent div

I'm having difficulty getting a color picker JavaScript widget to function properly within a webpage that contains unchangeable elements. Some of these elements are causing the color picker to be displayed far below the link once clicked. Here is a si ...

Accessing an unregistered member's length property in JavaScript array

I stumbled upon this unique code snippet that effectively maintains both forward and reverse references within an array: var arr = []; arr[arr['A'] = 0] = 'A'; arr[arr['B'] = 1] = 'B'; // When running on a node int ...

Requirements for using Angular JS and Node JS

With upcoming projects involving AngularJS and Node.js, I'm a bit apprehensive as I don't have much experience with JavaScript. Should I start by picking up a book on each technology, or is it essential to learn more about JavaScript first before ...

Refresh a section of the webpage without any mouse interactions

After receiving many helpful replies to my previous question, I am looking to update only a portion of a page instead of the whole page (with id='#colorbox'). I attempted modifying Rory McCrossan's code: by changing: window.location.relo ...

Is it possible to verify the presence of data in a database using the ajax method?

This piece of JavaScript code is responsible for validating mobile number data, among other information, and sending it to validate_user.php for storage. However, I only want to store the data of users whose mobile numbers exist in another table; otherwise ...

JavaScript script that parses innerHTML

Does the behavior of element.innerHTML = '<script>alert()</script>'; differ across browsers? Can I consistently expect innerHTML to not parse scripts? ...

Error: The parent selector "&" cannot be used in top-level selectors. $::webkit-input-placeholder

I am facing an issue while trying to run a legacy create-react-app that utilizes Sass. Initially, when I ran npm start, I encountered the error 'Cannot find module sass', which resembled the message found in this stack overflow post. To resolve t ...

Save the content from the page into a variable using JavaScript/jQuery

Is there a way to store the output of the_content() into a variable? Here is what I have attempted: <script type="text/javascript"> window.the_content = "<?php the_content(); ?>"; </script> Additionally, I tried this method: <?p ...

How to update state in React using complex objects

Within our React components, we are retrieving an object from a REST api (such as a Car), allowing users to modify it, and eventually save the changes. To streamline this process, we have developed a custom react hook for handling the state. An example im ...

What steps should be taken to develop a Hybrid Mobile App concept?

We are currently developing our first hybrid mobile application with a monetizable idea in mind. After conducting some research, it seems that to reach our end goal we will need: A Front End UI Framework: options include Ionic or AngularGap (although d ...

HighStock chart malfunctioning with inaccurate epoch datetime display

I am working on a project that involves creating a dynamic Highstock chart to showcase the daily influx of emails. The data is stored in a JSON file that gets updated every day, and you can see a snippet of it below: [{ "name": "Month", "data": [147199320 ...

Utilizing conditional formatting to set background colors in an HTML table

Our manufacturing company collects and documents data for the parts we produce. Currently, this information is logged on a spreadsheet with drawing dimensions in one column and actual measured values in another. The cell where the actual measured value i ...