How to update database after clicking on html element? - flask

In my flask application, I have a points column in the database, which is initialized to 0 on user registration. Now, I want to be able to update the points in database after clicking an html element.
class User(UserMixin, db.Model):
points = db.Column(db.Integer)
#bp.route('/activity1')
#login_required
def activity1():
return render_template('activity1.html', title='Activity 1')
Activity1.html has the point-generating html element
#bp.route('/register', methods=['GET', 'POST'])
def register():
...
form = RegistrationForm()
if form.validate_on_submit():
user.points = 0
db.session.add(user)
db.session.commit()
...
<a data-toggle="collapse" class="w3-large" href="#tip4" onclick="getPoints()">...</a>
<script>
function getPoints(){
points += 20; #How do i access the database.points in this case?
}
</script>

I'm not sure if I understand the code correctly, but are you asking how to update the number of points from activity1.html in the last code snippet? That won't work, the HTML is rendered on the server and once presented to the browser, there's no link between the two.
If you need to pass some data to the template while rendering it, you have to pass it in the render_template call, e.g.
render_template('activity1.html', title='Activity 1', user=user)
Then you can access it in the template like this:
<script>
function getPoints(){
points = {{ user.points|int }} + 20;
// post to backend to update data in database (using jQuery)
$.ajax({
type: 'POST',
contentType: 'application/json',
data: {
id: "{{ user.id }}",
points: points
},
dataType: 'json',
url: 'http://xxx/update_points',
success: function (e) {
// successful call
},
error: function(error) {
// an error occured
}
});
}
</script>
If you then want to update the user points in the database, you'll have to make a request to the server, which will take care of this. On the server side in Flask, define a view to handle this request:
#bp.route('/update_points', methods=['POST'])
def update_points():
data = request.get_json()
# don't know exactly what's the model and how to get the 'user' instance
user = User.get_user_by_id(data['id'])
user.points = data['points']
db.session.add(user)
db.session.commit()
Take it as an example code, I didn't test it and ommited quite a lot of details (e.g. how to get user instance in update_points etc.) Also, I might have missed what you are really asking for.

Related

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();
});

Connecting django signal to a button click

I'm trying to use a Django signal to toggle a model's boolean value to False from True when a button is clicked. I think that the Django sender would be the button click and the receiver would be the function that changes the boolean value. I'm not sure how to write out a button click as a signal sender however.
Here is my model with the Boolean value.
From models.py:
class User(AbstractUser):
is_blue = models.BooleanField(default=False)
Any thoughts on a what a signal would look like that take a button click and changes this value to True?
To change your model field, you need to create a separate function for it in your views, e.g.:
from django.http import JsonResponse
from xxx.models import User
def ajax_change_user(request):
is_blue= request.GET.get('is_blue', False)
# Get your User model
user = User.objects.get(pk=user_id)
try:
is_blue = True
user.save()
return JsonResponse({"success": True})
except Exception as e:
return JsonResponse({"success": False})
return JsonResponse(data)
Then you need to add a url for this view:
path('ajax/change_user', views.ajax_change_user, name='ajax_change_user')
Then in your html, you need to add a tag with the necessary class, e.g.:
{% csrf_token %}
Change
And then finally the javascript with ajax call part:
<script>
$(".change-user").on('click', function () {
var user_id = $(this).data('userid);
var is_blue = False # say you start with the status being false
$.ajax({
url: '/ajax/change_user/',
data: {
'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(),
'is_blue': is_blue
'user_id': user_id
},
dataType: 'json',
success: function (data) {
if (data.success) {
alert("ajax call was successful.");
is_blue = True # if button is clicked, make 'is_blue' True
}else{
alert("ajax call was not successful.");
}
}
});
});
</script>
This is just an example to get you started, you would need to alter it to suit your needs. You could for example add an if statement before the ajax call to check if is_blue is true or not, so that you can toggle the value.

Testing AJAX in Django

I want to test an AJAX call in my Django app.
What is does is adding a product to a favorite list. But I can't find a way to test it.
My views.py:
def add(request):
data = {'success': False}
if request.method=='POST':
product = request.POST.get('product')
user = request.user
splitted = product.split(' ')
sub_product = Product.objects.get(pk=(splitted[1]))
original_product = Product.objects.get(pk=(splitted[0]))
p = SavedProduct(username= user, sub_product=sub_product, original_product = original_product)
p.save()
data['success'] = True
return JsonResponse(data)
My html:
<form class="add_btn" method='post'>{% csrf_token %}
<button class='added btn' value= '{{product.id }} {{ sub_product.id }}' ><i class=' fas fa-save'></i></button
My AJAX:
$(".row").on('click', ".added", function(event) {
let addedBtn = $(this);
console.log(addedBtn)
event.preventDefault();
event.stopPropagation();
var product = $(this).val();
console.log(product)
var url = '/finder/add/';
$.ajax({
url: url,
type: "POST",
data:{
'product': product,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
datatype:'json',
success: function(data) {
if (data['success'])
addedBtn.hide();
}
});
});
The problem is that I pass '{{product.id }} {{ sub_product.id }}' into my views.
My test so far:
class Test_add_delete(TestCase):
def setUp(self):
self.user= User.objects.create(username="Toto", email="toto#gmail.com")
self.prod = Product.objects.create(
name=['gazpacho'],
brand=['alvalle'],
)
self.prod_2 = Product.objects.create(
name=['belvita'],
brand=['belvita', 'lu', 'mondelez'],
)
def test_add(self):
old_saved_products = SavedProduct.objects.count()
user = self.user.id
original_product = self.prod.id
sub_product = self.prod_2.id
response = self.client.post(reverse('finder:add', args=(user,))), {
'product': original_product, sub,product })
new_saved_products = SavedProducts.objects.count()
self.assertEqual(new_saved_products, old_saved_products + 1)
My test is not running and I get a SyntaxError 'product': original_product, sub_product. I know it's not the proper way to write it but my AJAX send the two ids with a space in between to the view.
If all you want to do is test if the data was actually saved, instead of just returning data['success'] = True you can return the whole entire new object... That way you can get back the item you just created from your API, and see all the other fields that may have been auto-gen (ie date_created and so on). That's a common thing you'll see across many APIs.
Another way to test this on a Django level is just to use python debugger
import pdb; pdb.set_trace() right before your return and you can just see what p is.
The set_trace() will stop python and give you access to the code scope from the command line. So just type 'l' to see where you are, and type(and hit enter) anything else that's defined, ie p which will show you what p is. You can also type h for the help menue and read the docs here

django - passing data from server to js function via class based view

Django 1.6.3 +
Need to pass data to a class based view. where I want my jquery function to handle the data passed from the server. How would that be done ?
1.
Create a javascript/jquery function in your view which makes an $.ajax({options}); call to the url you want to send & receive data from (See #4 for an example).
2.
Have your views.py file import the json & HttpResponse module.
import json
from django.http import HttpResponse
3.
Add a function in your views.py to handle the request
def ExampleHandler(request):
Within this function, you can access parameters like request.POST['paramname'] or request.GET['paramname']. See https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.GET for more information.
To return data to the ajax call, store your data in a dictionary like this:
result = {
'success': True,
'foo': bar,
'more': data
}
and return the json like this:
return HttpResponse(json.dumps(result), content_type="application/json")
4.
Your original javascript function will look similar to this now:
function exampleRequest() {
$.ajax({
type: 'POST',
url: '/url-mapped-to-your-view',
data: {data: 'some-data-to-send-to-views'}, // May need to add a CSRF Token as post data (eg: csrfmiddlewaretoken: "{{ csrf_token }}")
error: function() {
alert('There was an issue getting the data...');
},
success: function(data) {
// Accessing data passed back from request, handle it how you wish.
alert(data.foo);
alert(data.more);
}
)};
}
5.
Ensure the url you make the ajax call to is correctly mapped in urls.py
You can probably pass data via args or kwargs
in views.py
class YourView(TemplateView):
def get_context_data(self, **kwargs):
context = super(YourView, self).get_context_data(**kwargs)
context['yourdata'] = self.kwargs['data']
return context
in urls.py
url(r'(?P<data>\w+)$', YourView.as_view()),