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!