Django: combining method and class inside views to share same url - django

I'm working on Django project where I have an app which has a page with a drop down and a chart that is generated from data (which is queried from the database and passed into an API url). I'm using class based views and APIView and have a get method which is creating a response to pass some Json data into a url. I have the following class in my views.py set up and working.
views.py
class ChartData(APIView):
authentication_classes = []
permission_classes = []
def get(self, request, format=None):
#generated through code
data = {
"labels": all_times,
"default": all_data,
}
return Response(data)
In order have access to this data, I have my url set as:
url(r'^display/api/chart/data/$', views.ChartData.as_view()),
This data from the API is used to generate a ChartJS graph in my template html of this app. The chart is set up so that it seeks the Json data from the url display/api/chart/data/ and uses Ajax to populate itself. Here is how the chart is generated:
<script>
{% block jquery %}
var endpoint = 'display/api/chart/data/'
var defaultData = []
var defaultLabels = [];
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
defaultLabels = data.labels
defaultData = data.default
console.log(data)
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: defaultLabels,
datasets: [{
label: '# Measurable',
data: defaultData,
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
{% endblock %}
</script>
I also have another method in the same views file as follows:
views.py
def DropdownDisplay(request):
items= #query from database
if (request.method == 'POST' and request.is_ajax()):
print(request.POST)
return render(request, 'DisplayData/Display.html',{'dropdown':items})
This method is used to generate a dropdown in the page. The url for this is set up in the same urls.py file as follows:
url(r'^graph/', views.DropdownDisplay, name='Display-Dropdown')
Note: they are in the same views.py and urls.py file, I just separated them in this post for formatting purposes.
Now, I'm running into an issue. When I go to /display, the graph works, but the drop down does not. When I go to /display/graph, the drop down works but the graph does not. I can tell it is because in my urls.py, I have separate urls for each class and method, so they only work under their respective url.
However, I would like to combine them so that both the generation of the graph, and the population of the dropdown, work under one url, which will be /display.
How can I go about achieving this?

If you want them to be a part of the same page, both the functionalities should be inside a form under one view. If not, there should not be one single url for two separate functionalities. Your question is a bit ambiguous. If you can clearly state the functionality, would be helpful.

Related

Save Django Model when list_editable fields are changed in Django Admin change_list view

I have a Django Model which I'm trying to update from the Admin change_list view when a field that is listed in list_editable has a change event fired. Right now the only way to save the updates is by clicking a "Save" button and then the page reloads. I don't want the page to reload at all. I just want it to update the model asynchronously.
For example I have the following model.
class Example(models.Model):
name = models.CharField()
hide = models.BooleanField(default=False)
In the Admin Form I have
class ExampleAdmin(admin.ModelAdmin):
list_display = [
"name",
"hide"
]
list_editable = [
"name",
"hide"
]
When viewing the change list for Examples now I will see the values listed out with an editable text input for name and a checkbox for hide.
I would like to listen for events on those inputs and when they are fired send an async request to update the specific model.
UPDATE
This is what I have right now.
window.addEventListener("load", function() {
(function($) {
$(".field-name .vTextField").on("change",function (event) {
$('#changelist-form').submit()
})
$('#changelist-form').submit(function(event) { // On form submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
console.log(response)
},
error: function(e, x, r) { // on error..
console.log(e)
}
});
event.preventDefault()
return false;
});
})(django.jQuery);
})
I can see this firing in the network requests and can verify that the serialized data being sent is updated. The response is a 200, but when I refresh the page the data has not been updated.
UPDATE
At this point I'm giving up on sending this data to Django and will be sending the serialized data to a custom endpoint and parse through and save the data in a custom save function.
Within your Admin Model add the following
class ExampleAdmin(admin.ModelAdmin):
class Media:
js = ("js/admin/example.js")
list_display = [
"name",
"hide"
]
list_editable = [
"name",
"hide"
]
example.js
window.addEventListener("load", function() {
(function($) {
$(".field-name .vTextField").on("change",function (event) {
submit()
})
function getFormData($form){
var unindexed_array = $form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function(n, i){
indexed_array[n['name']] = n['value'];
});
return indexed_array;
}
function submit(){
$.ajax({
data: getFormData($('#changelist-form')),
type: "POST",
url: '/api/save-example',
success: function(response) {
console.log(response)
},
error: function(e, x, r) {
console.log(e)
}
});
}
})(django.jQuery);
})
I'm using Django Rest Framework so I created a POST endpoint, but you could also do this in a Django View that is listening for a POST.
When you execute the post Django will send the data categorized by the row number and field name, like so.
form-0-id : 1
form-0-name: example-name
form-0-hide: false
form-0-example_parent: 100
form-1-id : 2
form-1-name: example-name-two
form-1-hide: true
form-1-example_parent: 200
#api_view(["POST"])
def save_example(request):
try:
total_rows = int(request.POST.get("form-TOTAL_FORMS"))
prefix = "form-"
form_fields = {
"id": "id",
"name": "name",
"hide": "hide",
"example_parent": "example_parent_id",
}
for x in range(total_rows):
item = {}
for key, val in form_fields.items():
post_field = prefix + str(x) + "-" + key
field = val
if key == "id":
id = request.POST.get(post_field)
else:
item[field] = request.POST.get(post_field)
Example.objects.filter(id=id).update(**item)
return Response(status=status.HTTP_200_OK)
except Exception as e:
return Response(status=status.HTTP_404_NOT_FOUND)
Note
total_rows = int(request.POST.get("form-TOTAL_FORMS")) which lets you know how to loop through all the form data that is passed back.
This doesn't take different values into consideration. (i.e. Checkboxes will return an on value but no value if not checked.
You will need to update your save_example function accordingly.

django ajax get model data in JS variable

Trying to get my model data from django views.py in home.html javascript variable using AJAX.
So far I'm at :
Views.py:
class HomePageView(ListView):
model = Flights
template_name = 'home.html'
def flights_list(request):
flights = serializers.serialize("json", Flights.objects.all())
return JsonResponse({"flights": flights})
Ajax:
function get_data() {
$.ajax({
url: '', //Not sure what to put here.
datatype: 'json',
type: 'GET',
success: function (data) {
alert("Got data!")
locations = {{ flights }};
}
});
};
$(document).ready(function(){
setInterval(get_data,5000);
});
Every 5 seconds i'm getting alert "Got data!"
But when I'm trying to pass variable location = {{ flights }};
Then locations is empty.
in ajax url:'' i suppose to have my views.py location? as when trying to alert("Got data!" + data) then my whole html is in that data variable..
Am i doing something wrong here?
UPDATE:
My flights urls:
from django.urls import path
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'flights', views.FlightViewSet)
urlpatterns = [
path('',views.HomePageView.as_view(),name='home'),
]
Update 2:
Ok so I've found out what's wrong,
Changed urls.py:
urlpatterns = [
path('',views.HomePageView.as_view(),name='home'),
path('flights/', views.flightslist, name='flights')
]
Views.py:
def flightslist(request):
flights = serializers.serialize("json", Flights.objects.all())
return JsonResponse(flights, safe=False)
Had to add safe=False as no other way worked..
Update:
I've managed to sort it out by code:
function get_data() {
$.ajax({
url: 'flights/',
datatype: 'json',
type: 'GET',
success: function (data) {
alert("Got data!")
var locations = data;
}
});
};
$(document).ready(function(){
setInterval(get_data,5000);
});
How to convert var locations = data to dictionaries? As now it shows up as :
[{"model": "flightapp.flights", "pk": 390, "fields": and only then dictionary that i need.

Multiple Django subforms displayed with ajax in a main form but data not registered when subforms are submited (without error)

EDIT #1
well maybe because it is not clear in my head
and your are right saying Django forms are not intented to be used with ajax that why I wonder if there is way way doing what I want using Django forms without losing power of Django forms validation
I will try to clear my demand
considering this UI below
When user reach this "patient page" = main form (image 1), he can select "Inclusion form = subform (INCL-001 for instance) in the menu
I want the corresponding form to be displayed without refresh the page ; that why I have used ajax to display the corresponding form
If the corresponding form does not exist, it is a CREATION and a blank "Inclusion form" is displayed : user can enter data and save
If the corresponding form already exist, it is a UPDATE and a prefilled "Inclusion form" is displayed : user can update data and save or delete the form
what would be an elegant way of doing that?
I have a main form (patient.html) and I want to display different subforms (inclusion.html for instance) with ajax in this form.
I manage to display a subform when user click on a button in the main form
But, data are not stored when submitted and it is quite normal as no view is linked to this subform
I have read about this in different post but I miss the concept how to...
I thinks it is a common task with web so probably Django as an easy way to do it?
thanks for advices
urls.py
app_name='ecrf'
urlpatterns = [
path('', views.index, name='index'),
path('patient/<pk>', views.patient, name='patient'),
path('sub_form', views.sub_form, name='sub_form'),
]
views.py
def patient(request,pk):
patient = {"id":1,"num":'A-001',"dat":'Mon 11, novembre 2020',"arm":1,"doc":'Slater'}
return render(request, 'ecrf/patient.html', {'patient':patient})
def sub_form(request):
if request.is_ajax():
return JsonResponse(
{
'html_inclusion': render_to_string(
'ecrf/inclusion.html',
{
'form': InclusionForm,
'language': request.session.get('language')
},
request=request
),
},
status=200
)
js
$(document).ready(function () {
...
$("#add").on("click",function (event) {
var csrftoken = getCookie('csrftoken');
$.ajax({
type: "POST",
url: '/ecrf/sub_form',
data: {
csrfmiddlewaretoken: csrftoken,
},
dataType: 'html',
success: function (data) {
$("#sub_form").children().remove();
obj = JSON.parse(data);
$("#sub_form").append(obj.html_inclusion);
},
error: function (data) {
console.log('error');
}
});
});
$("body")
.on("click", '#inclusion', function (event) {
console.log('inclusion click')
})
});

Show loading gif until the django view performs the data processing and renders the template with this data

I have a django project where the page has multiple nav links representing different agents. On clicking any nav link, the urls.py redirects to nav specific view and the view needs to perform some processing to get the data needed to render the template. However as this is syncrhonous rendering it takes a long while to load data (in the order of 15-20s).
Below is my urls.py:
from django.urls import path
from . import views
app_name = 'agent'
urlpatterns = [
path('agent1/', views.agent1, name='agent1'),
path('agent2/', views.agent2, name='agent2'),
path('agent3/', views.agent3, name='agent3'),
path('agent4/', views.agent4, name='agent4'),
]
My views method looks as below:
def agent1(request):
agent_data = Agent1.objects.all()
agent_details = get_agent_details(agent_data)
return render(request, 'manager/data.html', {'agent_data': agent_data, 'agent_details': agent_details})
I am using the {{ agent_data.name }}, {{ agent_data.code }}, {{ agent_data.qty }} and {{ agent_data.price }} along with data from agent_details dictionary in my html to populate a table's rows. How should I change my view method, so that it loads the data via AJAX (javascript) in order to show a loading gif in the meantime and also provide me the data so that I can populate the table. Could someone help me with the Ajax code and the steps as I am new to this technology and not finding any help going through the online tutorials.
So for this to work with ajax, you'll need some javascript in manager/data.html which knows the url to fetch data from.
As an example, I've got an ajax setup which checks a given email address isn't already in use;
(function($) {
$(document).ready(function() {
var validateEmailURL = $section_user_signup.data('ajax-email-url');
function validateEmailUnique() {
var valid = true;
clearError($email);
// Fetch unique status of the provided email
$.ajax({
async: false,
url: validateEmailURL,
method: 'POST',
type: 'POST',
dataType: 'json',
data: {
'email': $email.val(),
'csrftoken': $form.find('input[name="csrfmiddlewaretoken"]').val()
},
success: function (response) {
valid = true;
},
error: function (response) {
setError($email, response["responseJSON"]["error"]);
valid = false;
}
});
return valid;
}
});
})(window.jQuery);
This javascript uses the data attribute of a div for the URL to check;
<div data-ajax-email-url="{% url 'account_ajax_validate_email' %}">
The view which the ajax call goes to looks like this;
def ajax_check_email_unique(request, *args, **kwargs):
"""
Return an JsonResponse to identify if an email is unique.
"""
if not request.is_ajax():
return HttpResponseBadRequest()
if request.is_ajax and request.method == "POST":
email = request.POST.get('email')
if email_address_exists(email):
return JsonResponse(
{
"error":
"Email address already exists. Click "
f"here "
"to login"
},
status=400
)
return JsonResponse(
{"email": email},
status=200
)
# some error occurred
return JsonResponse({"error": ""}, status=400)
The important thing for any view which will be used by javascript is that you return a JsonResponse.
So if I was you, I'd setup a new view for ajax, and that makes your existing one really simple;
def agent1_ajax(request):
agent_data = Agent1.objects.all()
agent_details = get_agent_details(agent_data)
return JsonResponse({
"agent_data": agent_data, "agent_details": agent_details
}, status=200)
def agent1(request):
return render(request, 'manager/data.html', {})
And as far as a loading gif goes, you'd need an element that contains the gif and then you can bind to the ajax event to show/hide;
$(document).ajaxStart(function() {
$("#loading").show();
});
$(document).ajaxStop(function() {
$("#loading").hide();
});

Django - retrieve form data

I am trying to send a form through ajax call to django view as follows:
$.ajax({
type: 'POST',
url: "{% url 'edit_experience' %}",
data: {
item_id : itemId,
form: $("#sample-form").serialize()
},
beforeSend : function() {
},
success: function (data) {
},
error: function(data) {
},
complete : function() {
}
});
I am able to see the data being posted to the http server:
form role=Fresher&organization=TestOrganization&description=Hard+work+pays
item_id 3
My problem is in the server side where I am trying to fetch the data. I am able to access the item_id but I am having a problem accessing the form elements:
In Django View:
def edit_experience(request):
request.POST['form']['role']
return ....
This does not fetch the role. What is the correct way to fetch all the form attributes??
Kindly help. Thanks in advance.
To fetch attributes from the querystring you can use QueryDict:
from django.http import QueryDict
d = QueryDict(request.POST['form'])
role = d['role']