I'm new to django. I want to manage my database with custom methods inside the views file. for example, I have this code I would like to run with javascript - I wrote this code:
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),
]
now, the problem is, that for every new function that I want to create in the views.py, I need to add another line in the urls.py.
my question is - if there a way to create a class with all of the custom methods, and access them with one url and 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),
]
I came from asp.net background where I wrote classes with functions that ran queries and that it how I managed my database, so can I do the same here?
Thanks In Advance!
You can use Class Based View to implement your views as Python objects instead of functions, but you can't call a class function with Ajax.
Related
I am trying to submit localstorage data via a POST request using the below jquery ajax method. How should I write my view so I can Parse my JSON object and get a hold of "product_id" to execute the below command in my Django view. Please see a copy of my view below.
Trying since one week, but I failed to fix the issue
Is there any better way of achieving this ?
My Ajax:
$(document).ready(function() {
var compare = localStorage.getItem("comparisionItems");
var compareObj = JSON.parse(compare);
var data_url = window.location.href;
console.log(compare)
console.log(compareObj)
$.ajax({
url: data_url,
type: "POST",
data: {'compare_id': compareObj },
headers: { "X-CSRFToken": $.cookie("csrftoken") },
success: function (result) {
console.log("Success")
},
});
});
and My Views:
def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
compare_id= request.POST.getlist('compare_id[itemIds]')
product = get_object_or_404(Products, id=compare_id)
context={ 'product':product}
return render (request, './compare.html', context)
Actually my localStorage is on following format:
("comparisionItems"({ images: products, itemIds: itemIds }));
Can you please help me how can I pass itemIds to views and return item from views for the itemsIds?
Console log for console.log(compareObj)
https://imgur.com/MxdZrgy
since .is_ajax() is deprecated you cant use that, but you can check if the request is an XMLHttpRequest like below.
from django.shortcuts import get_object_or_404
def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
compare_id = request.POST.get('compare_id')
product = get_object_or_404(Products, product_id=id)
context={ 'product':product,}
return render (request, './ecommerce/compare.html', context)
note; the get_object_or_404 is just a shortcut for:
try:
product = Products.objects.get(product_id=id)
except:
raise Http404
I am pretty new to Django and I am trying to figure out how to add content dynamically coming from a python script without reloading a page.
Currently, I have two functions in my views.py file. One handles uploading a file (home), and the other handles calling a python script and handling the file (handle). The reason I separated it like this is because I want to sequentially populate a HTML table as the python script works with the uploaded file.
However, my ajax function is not receiving any data from the handle function's http response and I am not sure why. Neither the success nor the error functions are being called. This is really strange because the print statement in the handle function in views.py prints successfully with data.
Views.py
i=0
uploaded_file = None
def home(request):
if (request.method == 'POST'):
file_form = UploadFileForm(request.POST, request.FILES)
if file_form.is_valid():
global uploaded_file
uploaded_file = request.FILES['file']
print(uploaded_file)
else:
file_form = UploadFileForm()
return render(request, 'personal/home.html', {'form': file_form})
def handle(request):
# TODO make ajax wait for a response from 'home'
# so I don't have to wait for 1 second
time.sleep(1)
data = {}
data['Name'] = fileName(uploaded_file)
if(request.is_ajax()):
print(data) # prints succesfully
return HttpResponse(json.dumps(data),
content_type="application/json")
home.html
<script type = "text/javascript" language = "javascript">
function post_tables(data) {
alert(data)
}
$(document).ready(function(post_tables) {
$("#upload").click(function(event){
$.ajax( {
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "get",
url:'/handler',
success: function(data) {
console.log("over here")
post_tables(data)
},
error: function(data) {
console.log("down here")
post_tables("error being thrown")
}
});
});
});
</script>
urls.py
urlpatterns = [
path(r'', views.home, name='home'),
path(r'handler', views.handle, name='handle'),
]
I explained the whole process ajax django to you. Perhaps your problem will be solved. good luck.
views.py
def handle(request):
if request.method == 'POST':
data = request.POST
field_example = data.get('field_example')
return JsonResponse(data)
else:
data = request.GET
field_example = data.get('field_example')
return JsonResponse(data)
home.html
<form id="upload">
{% csrf_token %}
<input type="text" name=field_example>
.
.
.
</form>
urls.py
urlpatterns = [
path(r'', views.home, name='home'),
path(r'handler/', views.handle, name='handle'),
]
js code in home.html:
$("#upload").submit(function (e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "{% url 'handle' %}",
type: 'GET',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log("over here")
post_tables(data)
},
error: function (data) {
console.log("down here")
post_tables("error being thrown")
}
});
});
My template.html:
...
<button class="btn btn-success" onclick="save_post(event, 'publish')">Publish</button>
...
My javascript.js:
function save_post(event, action) {
event.preventDefault();#new line
var tag_string=document.getElementById('id_tags').value;
if (action=='publish' || action=='draft') {
var url_post='/blog/post/new/'
} else {
var url_post='/blog/post_edit/'
};
$.ajax({type: 'POST',
url: url_post,
data: {
tagstring: tag_string,
action: action
},
success: function (lista) {
//code
}
});
};
My views.py:
#staff_member_required
def post_new(request):
context_dict=[]
if request.method == "POST":
if request.is_ajax():
#code
...
else:
form = PostForm()
return render(request, 'blog/post_edit.html', context_dict)
My url.py:
app_name = 'blog'
urlpatterns = [
...
path('post/new/', views.post_new, name='post_new'),
path('post/<int:pk>/edit/', views.post_edit, name='post_edit'),
...
My views is called by the url (browser), then the button call a javascript function and it call (with ajax) again the same view, this time with request.method = "POST" and this works, but request.is_ajax() gives False.
For call post_edit (probabily) I need the id of the post. Where can I get it?
Should I pass it to save_post() from the template?
Edit: ignore these lines below
Also should I use preventDefault() somewhere?
Thank you
Edit: now I use preventDefault() but it gives this error:
Not Found: /blog/post_new/
[26/Jan/2018 19:07:20] "POST /blog/post_new/ HTTP/1.1" 404 10871
and ajax dosn't call the view. Edit: I solved this problem, but I continue tomorrow :)
Your Ajax code some problems and view is correct
I have attached my Code attached Image and code
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'myajaxview', // the url where we want to POST
data :{
'csrfmiddlewaretoken': '{{csrf_token}}',
'text': text,
'search': search,
'email': email,
'url': url,
'telephone': telephone,
'password': password,
'number': number,
},
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
I'm trying to display the error messages that I provided on my forms, but it only display the id name instead of error message.
Here's my code
Form.py
class SecurityCode(forms.Form):
sCode = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(id="scode", name="scode", required=True, size=25, placeholder=" Security Code")), error_messages={ 'invalid': "This value must contain only letters, numbers and underscores." })
Views.py
def security(request):
if request.method == 'POST':
securityField = SecurityCode(request.POST)
if taxpayerField.is_valid():
return HttpResponse("success")
else:
return HttpResponse(taxpayerField.errors)
Note: I'm trying to get the error message in this views not on my html because I'm trying to alert that on my javascript. Also this is just my sample code not the original one.
You can try this:
views.py:
from django.http import JsonResponse
def security(request):
form = SecurityCode(request.POST)
if not form.is_valid():
return JsonResponse({
'success': False,
'err_code': 'invalid_form',
'err_msg': form.errors,
})
#[...] Actions if form is valid ...
return render(request, 'template.html')
javascript code:
def submit_form(){
var data = {
field1: '...',
field2: '...',
csrfmiddlewaretoken: 'csrftoken',
};
$.ajax({
url: '/submit/form/',
method: 'POST',
data: data,
dataType: 'json',
success: function (data){
if (data.success){
// Actions ...
}
else if (data.err_code === 'invalid_form'){
for(var key in data.err_msg){
console.log('[error] for ' + key + ': ' + data.err_msg[key][0]);
}
}
},
});
}
I use console.log to illustrate the recovery of the error message for each field.
I know, i know, there are already some questions on this subject and believe my i've tried many many thing but still, i can't make it work.
I had a page with the form, tu upload an img with a comment (so a textarea and a file input). The thing is, i don't want to have a specific page for this form, so i have a popin with the form in a page. So i decided to do it in ajax (so the user can stay on the page and upload severals photos).
But I keep having a mistake, 'the comment field is required'. It looks like the form sent is empty. Following documentation and many (MANY) advices this is how i did it :
Form.py
class UploadPhotoForm(ModelForm):
class Meta:
model = Photo
fields = ['picture', 'comment']
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request", None)
super(UploadPhotoForm, self).__init__(*args, **kwargs)
def save(self):
photo = super(UploadPhotoForm, self).save(commit=False)
artist = Artists.objects.get(user=self.request.user)
photo.artist = artist
photo.save()
return photo
views.py (the one handling the form : i changed it when i wanted to make ajax):
#login_required
#require_POST
def upload_photo_artist(request):
form = UploadPhotoForm(request.POST, request.FILES, request=request)
if form.is_valid():
form.clean()
form.save()
response = {
'code': 1,
'message': 'success',
}
return HttpResponse(
json.dumps(response),
content_type='application/json'
)
else:
response = form.errors.as_json()
return HttpResponse(
json.dumps(response),
content_type='application/json'
)
And the JS part :
$('#upload_photo').submit(function(e){
e.preventDefault();
var csrftoken = getCookie('csrftoken');
var data = new FormData($(this)[0]);
data.append('csrfmiddlewaretoken', csrftoken);
//data.append('comment', $(this).find('div.input-field').find('textarea').val());
//data.append('photo', $(this).find('div.file-field').find('input:file')[0]);
$.ajax({
url: "/photo/upload",
type: "POST",
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
data: data,
processData: false,
contentTYpe: false,
success: function(data) {
if(data['code']== 1) {
location.reload();
}
else {
alert(data);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
So it looks like the formData object send is just an empty thing, but i've read the documentation and some examples and i don't see what am I doing wrong here.
You can see in comment the append() method of FormData object. I've tried to just declare a new FormData object empty and add then the fields.
In last try, i had directly the CSRFToken in the FormData object, but still, doesn't work.
If someone can help, that'd be great !