How can I get data fro QuerySet dict received via AJAX to Django View to create model objects ?
I have a model and want to create record based on the data recieved to my view from a AJAX call:
In models.py
--------------------------------------
class Items(models.Model):
item = models.CharField (max_length=128, blank=False,null=False)
qty = models.CharField (max_length=128, blank=False,null=False)
price = models.CharField (max_length=128, blank=False,null=False)
In views.py
--------------------------------------
if request.is_ajax():
if request.method == 'GET':
json_data = request.GET
print("LET'S DUMP THE DATA NOW!!")
data = json.dumps(json_data)
print(data)
Output to console:
I am recieving a dictionary from ajax to my view like this:
--------------------------------------
{"deals[0][Price]": "400", "deals[1][Item]": "Diet Donut", "deals[2][Price]": "180", "deals[1][Price]": "100", "deals[0][Item]": "Donut 4", "deals[2][Item]": "HazelNut Donut", "deals[1][Quantity]": "1", "deals[0][Quantity]": "4", "deals[2][Quantity]": "10"}
HTML-JS part
--------------------------------------
Page1.html
<script>
var items = [];
var qtys = [];
$(document).ready(function() {
var deal_collection = {
deals:[]
};
var jsonData = {};
// Getting data on a CLICK here for the variables
$('a[id^="tag"]').click(function() {
var index=$(this).index()-1;
var text = $(this).text();
var inv = {{ inv_all|safe }};
var item = inv[index].fields.item_name;
var qty = inv[index].fields.quantity;
var price = inv[index].fields.price;
// Adding to array
deal_collection.deals.push({
"Item":item,
"Quantity":qty,
"Price":price
});
});
});
//Saving deal_collection to localStorage so that it can be retireved on the Next page
$('#ajax_call').click(function(){
alert("AJAX Call Clicked");
console.log("AJAX Call clicked");
if (typeof(Storage) !== "undefined") {
localStorage.setItem('deal_array',JSON.stringify(deal_collection))
console.log("Data stored to storage")
} else {
// Sorry! No Web Storage support..
alert('No Storage available')
}
});
</script>
Page2.html:
<script>
var arr = JSON.parse(localStorage.getItem("deal_array"));
$.each(arr, function(i) {
console.log(arr[i]);
});
var msg = "Success !!!"
$.ajax({
url: '{% url 'ajax' %}',
type: 'GET',
data: arr,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
alert(msg);
}
});
});
</script>
/r/django
https://redd.it/6vp3hu
I have a model and want to create record based on the data recieved to my view from a AJAX call:
In models.py
--------------------------------------
class Items(models.Model):
item = models.CharField (max_length=128, blank=False,null=False)
qty = models.CharField (max_length=128, blank=False,null=False)
price = models.CharField (max_length=128, blank=False,null=False)
In views.py
--------------------------------------
if request.is_ajax():
if request.method == 'GET':
json_data = request.GET
print("LET'S DUMP THE DATA NOW!!")
data = json.dumps(json_data)
print(data)
Output to console:
I am recieving a dictionary from ajax to my view like this:
--------------------------------------
{"deals[0][Price]": "400", "deals[1][Item]": "Diet Donut", "deals[2][Price]": "180", "deals[1][Price]": "100", "deals[0][Item]": "Donut 4", "deals[2][Item]": "HazelNut Donut", "deals[1][Quantity]": "1", "deals[0][Quantity]": "4", "deals[2][Quantity]": "10"}
HTML-JS part
--------------------------------------
Page1.html
<script>
var items = [];
var qtys = [];
$(document).ready(function() {
var deal_collection = {
deals:[]
};
var jsonData = {};
// Getting data on a CLICK here for the variables
$('a[id^="tag"]').click(function() {
var index=$(this).index()-1;
var text = $(this).text();
var inv = {{ inv_all|safe }};
var item = inv[index].fields.item_name;
var qty = inv[index].fields.quantity;
var price = inv[index].fields.price;
// Adding to array
deal_collection.deals.push({
"Item":item,
"Quantity":qty,
"Price":price
});
});
});
//Saving deal_collection to localStorage so that it can be retireved on the Next page
$('#ajax_call').click(function(){
alert("AJAX Call Clicked");
console.log("AJAX Call clicked");
if (typeof(Storage) !== "undefined") {
localStorage.setItem('deal_array',JSON.stringify(deal_collection))
console.log("Data stored to storage")
} else {
// Sorry! No Web Storage support..
alert('No Storage available')
}
});
</script>
Page2.html:
<script>
var arr = JSON.parse(localStorage.getItem("deal_array"));
$.each(arr, function(i) {
console.log(arr[i]);
});
var msg = "Success !!!"
$.ajax({
url: '{% url 'ajax' %}',
type: 'GET',
data: arr,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
alert(msg);
}
});
});
</script>
/r/django
https://redd.it/6vp3hu
reddit
How can I get data fro QuerySet dict received via AJAX... • r/django
I have a model and want to create record based on the data recieved to my view from a AJAX call: In...
Jupytercon Notebooks?
Is there a place or could this be a place to post notebooks/resources from Jupytercon for those not able to attend?
/r/JupyterNotebooks
https://redd.it/6vk4q8
Is there a place or could this be a place to post notebooks/resources from Jupytercon for those not able to attend?
/r/JupyterNotebooks
https://redd.it/6vk4q8
reddit
Jupytercon Notebooks? • r/JupyterNotebooks
Is there a place or could this be a place to post notebooks/resources from Jupytercon for those not able to attend?
Need help with SQL-Alchemy
Hi, I am not sure if this make sense but I have two models, Person & Employee with respective persons and employees tables. I want to have it so that the employees table has a column that keeps track of the id of person who created it. Lastly, I would like to display rows from the employees table filtered by the column that was used to keep track of the id of the person who created it. How can I do this? An example would be helpful. Thanks
/r/flask
https://redd.it/6vcj0h
Hi, I am not sure if this make sense but I have two models, Person & Employee with respective persons and employees tables. I want to have it so that the employees table has a column that keeps track of the id of person who created it. Lastly, I would like to display rows from the employees table filtered by the column that was used to keep track of the id of the person who created it. How can I do this? An example would be helpful. Thanks
/r/flask
https://redd.it/6vcj0h
reddit
Need help with SQL-Alchemy • r/flask
Hi, I am not sure if this make sense but I have two models, Person & Employee with respective persons and employees tables. I want to have it so...
flask api and incremental testing
I am working on my first flask api, and I must test it because I'll be using it for a task that's rather sensitive. The issue is when I'm testing the CRUD part of the api I am not using unit tests which is bothering me as I ended up using incremental testing. Any tips or resources I could read to get an idea how to test CRUD operations with unit tests ?
/r/flask
https://redd.it/6qnd66
I am working on my first flask api, and I must test it because I'll be using it for a task that's rather sensitive. The issue is when I'm testing the CRUD part of the api I am not using unit tests which is bothering me as I ended up using incremental testing. Any tips or resources I could read to get an idea how to test CRUD operations with unit tests ?
/r/flask
https://redd.it/6qnd66
reddit
flask api and incremental testing • r/flask
I am working on my first flask api, and I must test it because I'll be using it for a task that's rather sensitive. The issue is when I'm testing...
[D] Andrew Ng's "Structuring a ML Project" summary in a diagram
https://medium.com/@erogol/designing-a-deep-learning-project-9b3698aef127
/r/MachineLearning
https://redd.it/6vplgr
https://medium.com/@erogol/designing-a-deep-learning-project-9b3698aef127
/r/MachineLearning
https://redd.it/6vplgr
Medium
Designing a Deep Learning Project
There are numerous on-line and off-line technical resources about deep learning. Everyday people publish new papers and write new things…
I wrote LaTeXiPy, a package which allows you to easily generate plots in multiple formats, and can play well with LaTeX!
https://github.com/masasin/latexipy
/r/Python
https://redd.it/6vpcnf
https://github.com/masasin/latexipy
/r/Python
https://redd.it/6vpcnf
GitHub
GitHub - masasin/latexipy: Generate beautiful plots for LaTeX using your existing matplotlib-based code.
Generate beautiful plots for LaTeX using your existing matplotlib-based code. - masasin/latexipy
Prevent modification of model through model/manager/queryset methods
Hello everybody,
I have a model which needs complex logic for update, creation and deletion.
I would like to have only one custom manager method to handle creation (let's call it `new`), one model method to handle deletion and prevent all the others.
My question is : Is there other methods that can modify models besides the ones below? Is there any way to know if I'm not missing a method that can modify models (other than reading the whole documentation)?
Here is what I have now :
class MyModelQuerySet(models.QuerySet):
def update(self, *args, **kwargs):
raise ValueError("Use 'new' method from manager instead.")
def delete(self):
raise ValueError("Use 'delete' method from model instead.")
class MyModelManager(models.Manager):
def get_queryset(self):
return MyModelQuerySet(self.model, using=self._db)
def create(self, *args, **kwargs):
raise ValueError("Use 'new' method from manager instead.")
def get_or_create(self, *args, **kwargs):
raise ValueError("Use 'new' method from manager instead.")
def update_or_create(self, *args, **kwargs):
raise ValueError("Use 'new' method from manager instead.")
def new(self, *args, **kwargs):
obj = self.model()
# Insert complex logic here
super(MyModel, obj).save()
class MyModel(models.Model):
def save(self, *args, **kwargs):
raise ValueError("Use 'new' method from manager instead.")
def delete(self, *args, **kwargs):
# Insert another complex logic here
super().delete(*args, **kwargs)
Thanks in advance for any bit of advice!
/r/django
https://redd.it/6vrbhy
Hello everybody,
I have a model which needs complex logic for update, creation and deletion.
I would like to have only one custom manager method to handle creation (let's call it `new`), one model method to handle deletion and prevent all the others.
My question is : Is there other methods that can modify models besides the ones below? Is there any way to know if I'm not missing a method that can modify models (other than reading the whole documentation)?
Here is what I have now :
class MyModelQuerySet(models.QuerySet):
def update(self, *args, **kwargs):
raise ValueError("Use 'new' method from manager instead.")
def delete(self):
raise ValueError("Use 'delete' method from model instead.")
class MyModelManager(models.Manager):
def get_queryset(self):
return MyModelQuerySet(self.model, using=self._db)
def create(self, *args, **kwargs):
raise ValueError("Use 'new' method from manager instead.")
def get_or_create(self, *args, **kwargs):
raise ValueError("Use 'new' method from manager instead.")
def update_or_create(self, *args, **kwargs):
raise ValueError("Use 'new' method from manager instead.")
def new(self, *args, **kwargs):
obj = self.model()
# Insert complex logic here
super(MyModel, obj).save()
class MyModel(models.Model):
def save(self, *args, **kwargs):
raise ValueError("Use 'new' method from manager instead.")
def delete(self, *args, **kwargs):
# Insert another complex logic here
super().delete(*args, **kwargs)
Thanks in advance for any bit of advice!
/r/django
https://redd.it/6vrbhy
reddit
Prevent modification of model through... • r/django
Hello everybody, I have a model which needs complex logic for update, creation and deletion. I would like to have only one custom manager...
Created this web application using Flask. Please let us know your reviews about it.
https://pageone.herokuapp.com
/r/flask
https://redd.it/6vsean
https://pageone.herokuapp.com
/r/flask
https://redd.it/6vsean
JQuery dropdown menu not working
I am in the middle of creating a very basic website and would like to use a drop down menu in the navigational bar.
I have included the Javascript library above my code but the dropdown fails to open when I click on it. You notice I have it in 2 places at the moment to see if it would work if I placed it in the head section but it doesn't make a difference.
I am just running it through my command line at the moment if that matters.
My code can be found here: https://pastebin.com/4qShX7zG
Thanks!
/r/flask
https://redd.it/6vsl1p
I am in the middle of creating a very basic website and would like to use a drop down menu in the navigational bar.
I have included the Javascript library above my code but the dropdown fails to open when I click on it. You notice I have it in 2 places at the moment to see if it would work if I placed it in the head section but it doesn't make a difference.
I am just running it through my command line at the moment if that matters.
My code can be found here: https://pastebin.com/4qShX7zG
Thanks!
/r/flask
https://redd.it/6vsl1p
Pastebin
[HTML] <script src="h - Pastebin.com
I'm struggling to learn how to upload/display images
Hey guys,
Newbie here.
I'm struggling to upload an image in a form. Right now, after setting an ImageField to my models:
imagem = models.ImageField(blank=True,upload_to = 'imagens/')
and adding to settings.py
MEDIA_ROOT = [os.path.join(BASE_DIR,'imagens')]
MEDIA_URL = '/media/'
the image field shows on the post form, but the image doesn't upload. If I try to upload on the admin, I get this error:
TypeError at /admin/posts/post/3/change/
expected str, bytes or os.PathLike object, not list
Is there an easy way to understand the basic steps for image handling?
Pillow is installed
/r/django
https://redd.it/6vtx01
Hey guys,
Newbie here.
I'm struggling to upload an image in a form. Right now, after setting an ImageField to my models:
imagem = models.ImageField(blank=True,upload_to = 'imagens/')
and adding to settings.py
MEDIA_ROOT = [os.path.join(BASE_DIR,'imagens')]
MEDIA_URL = '/media/'
the image field shows on the post form, but the image doesn't upload. If I try to upload on the admin, I get this error:
TypeError at /admin/posts/post/3/change/
expected str, bytes or os.PathLike object, not list
Is there an easy way to understand the basic steps for image handling?
Pillow is installed
/r/django
https://redd.it/6vtx01
reddit
I'm struggling to learn how to upload/display images • r/django
Hey guys, Newbie here. I'm struggling to upload an image in a form. Right now, after setting an ImageField to my models: imagem =...
[D] CVPR tutorial on "Mathematics of Deep Learning"
https://www.youtube.com/watch?v=Mdp9uC3gXUU
/r/MachineLearning
https://redd.it/6vqpxc
https://www.youtube.com/watch?v=Mdp9uC3gXUU
/r/MachineLearning
https://redd.it/6vqpxc
YouTube
Tutorial : Mathematics of Deep Learning - Part 1
Global Optimality in Deep Learning, René Vidal
(Johns Hopkins Univ.)
The past few years have seen a dramatic
increase in the performance of recognition systems
thanks to the introduction of deep networks for
representation learning. However, the mathematical…
(Johns Hopkins Univ.)
The past few years have seen a dramatic
increase in the performance of recognition systems
thanks to the introduction of deep networks for
representation learning. However, the mathematical…
How use Class-based views to create a user registration?
I was wondering how can I use class based views to create a user registration because I think I can do this with a ModelForm and do all the validation in this and after using a CreateView is this correct? Or should I use an only a CreateView.
Also, if anyone has any tutorial to do this to help me understand the use of clean() on the form, how validate?
Yea, silly question :c
/r/django
https://redd.it/6vugb9
I was wondering how can I use class based views to create a user registration because I think I can do this with a ModelForm and do all the validation in this and after using a CreateView is this correct? Or should I use an only a CreateView.
Also, if anyone has any tutorial to do this to help me understand the use of clean() on the form, how validate?
Yea, silly question :c
/r/django
https://redd.it/6vugb9
reddit
How use Class-based views to create a user registration? • r/django
I was wondering how can I use class based views to create a user registration because I think I can do this with a ModelForm and do all the...
Changing a model's attribute from CharField to ForeignKey makes the object unuseable and returns "unknown NAME_id"
Say I had the following model:
class greatModel(models.Model):
attribute = models.CharField(max_length=100)
and life was good. But then another dev tells me "hey, I actually have a whole model called `attribute` in another app `HIS_APP` on this project! Just make a ForeignKey. Sounds great, so I do:
class greatModel(models.Model):
attribute = models.ForeignKey('HIS_APP.attribute', on_delete=models.CASCADE)
but now EVERYTHING I do with this model including migrations will fail on:
django.db.utils.OperationalError: (1054, "Unknown column 'attribute_id' in 'where clause'")
Any idea where I might be going wrong? I've tried dropping/remaking the model/table but that was of no use.
/r/django
https://redd.it/6vvcyq
Say I had the following model:
class greatModel(models.Model):
attribute = models.CharField(max_length=100)
and life was good. But then another dev tells me "hey, I actually have a whole model called `attribute` in another app `HIS_APP` on this project! Just make a ForeignKey. Sounds great, so I do:
class greatModel(models.Model):
attribute = models.ForeignKey('HIS_APP.attribute', on_delete=models.CASCADE)
but now EVERYTHING I do with this model including migrations will fail on:
django.db.utils.OperationalError: (1054, "Unknown column 'attribute_id' in 'where clause'")
Any idea where I might be going wrong? I've tried dropping/remaking the model/table but that was of no use.
/r/django
https://redd.it/6vvcyq
reddit
Changing a model's attribute from CharField to... • r/django
Say I had the following model: class greatModel(models.Model): attribute = models.CharField(max_length=100) and life was good. But...
Best Django books to start with?
Hi all,
I have some rookie big data py 2.7 experience. I want to get into Django and web apps and websites. Since I already has a very basic py understanding, it just makes sense to work with Django. Does anyone have any good books on amazon they recommend for beginners that really walks you through and explains concepts well?
/r/djangolearning
https://redd.it/6vvw3v
Hi all,
I have some rookie big data py 2.7 experience. I want to get into Django and web apps and websites. Since I already has a very basic py understanding, it just makes sense to work with Django. Does anyone have any good books on amazon they recommend for beginners that really walks you through and explains concepts well?
/r/djangolearning
https://redd.it/6vvw3v
reddit
Best Django books to start with? • r/djangolearning
Hi all, I have some rookie big data py 2.7 experience. I want to get into Django and web apps and websites. Since I already has a very basic py...
[R] CS281: Advanced Machine Learning
http://www.seas.harvard.edu/courses/cs281/
/r/MachineLearning
https://redd.it/6vx171
http://www.seas.harvard.edu/courses/cs281/
/r/MachineLearning
https://redd.it/6vx171
reddit
[R] CS281: Advanced Machine Learning • r/MachineLearning
4 points and 4 comments so far on reddit
What language features makes Python positively stand out for you?
I'm curious what language features you *love* about Python that keep you coming back and make you enjoy the development experience.
For me I'd have to say a short list would be list/dict comprehension, as well as decorators.
What about you?
/r/Python
https://redd.it/6vtcdq
I'm curious what language features you *love* about Python that keep you coming back and make you enjoy the development experience.
For me I'd have to say a short list would be list/dict comprehension, as well as decorators.
What about you?
/r/Python
https://redd.it/6vtcdq
reddit
What language features makes Python positively stand... • r/Python
I'm curious what language features you *love* about Python that keep you coming back and make you enjoy the development experience. For me I'd...
This project was borne out of our experiences at YunoJuno with 'expiring links' - which is a common use case of providing users with a URL that performs a single action, and may bypass standard authentication.
https://github.com/yunojuno/django-request-token
/r/django
https://redd.it/6vxax4
https://github.com/yunojuno/django-request-token
/r/django
https://redd.it/6vxax4
GitHub
GitHub - yunojuno/django-request-token: Django app that uses JWT to manage one-time and expiring tokens to protected URLs. Not…
Django app that uses JWT to manage one-time and expiring tokens to protected URLs. Not related to DRF. - yunojuno/django-request-token
What hack can I do to allow me to use the algorithmicx latex extension in my notebook?
I've found exactly one answer to this topic online and it says MathJax doesn't do it.
Is there any non-portable, slightly hacky way of getting this to work? Something that would render to jpeg and embed that on the page?
/r/IPython
https://redd.it/6vxyjr
I've found exactly one answer to this topic online and it says MathJax doesn't do it.
Is there any non-portable, slightly hacky way of getting this to work? Something that would render to jpeg and embed that on the page?
/r/IPython
https://redd.it/6vxyjr
reddit
What hack can I do to allow me to use the algorithmicx... • r/IPython
I've found exactly one answer to this topic online and it says MathJax doesn't do it. Is there any non-portable, slightly hacky way of getting...