I have a webapp build in Python 2.6 and Django.
I am trying to send parameters to the HTML page but it seems that the HTML page is refreshing to the default values all the time.
Meaning i can see that movetobi is being called but it looks like the moment movebi return the value the page is reloaded again
View.py
def adminoperation(request):
return render(request,'app/adminoperation.html',{'some_flag':'999999'})
def movetobi(request):
if 'check' in request.POST and request.POST.get('check'):
data= {'newtest':3}
return JsonResponse(data, safe=False)
adminoperation.html
{% extends "app/layout.html" %}
{% block content %}
<p>Adminstration site for FTMS 2017</p>
<h2> {{mssg}}</h2>
<p>{{ mssg2 }} </p>
<p>{{ mssg3 }} </p>
<form id="data_form" method="post" enctype="multipart/form-data">
{% csrf_token %}
<button id="run_reports" type="submit" name="action" value="commit">Run Reports For BI</button>
<br> <br>
<button id="Rollback" type="submit" name="action"
value="commit">Rollback</button>
input type="hidden" id="commitok" name="commitok" value="{{ some_flag }}" />
</form>
{% endblock %}
{% block scripts %}
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<script>
$(function () {
$('#run_reports').click(function () {
$.ajax({
type: "POST",
url: 'movetobi',
data: {
'check' : '1',
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function (data){
if (data['newtest']==3) {
confirm("You are trying to run a month that allready exist");
}},
error: function(data){
if (data['newtest']==5) {
confirm("test");
}}
});
});
});
</script>
{% endblock %}
$('#run_reports').click(func) will not prevent the form from being submitted directly by the browser. You have to get the click event and call preventDefault() on it:
$('#run_reports').click(function(evt) {
evt.preventDefault();
# your code here
})
Related
I know javascript a little. But in a tutorial I have to add some jquery and ajax functionality.
here is a form:
<form class="form-product-ajax" method="POST" action="{% url 'carts:update' %}" class="form">
{% csrf_token %}
<input type="hidden" name="product_id" value=" {{p roduct.id}} "/>
{% if in_cart %}
<button type="submit" class="btn btn-link btn-sm" style="padding:0px;cursor:pointer;" name="button">Remove?</button>
{% else %}
<span class="submit-span">
{% if product in cart.products.all %}
In cart<button type="submit" class="btn btn-danger" name="button">Remove?</button>
{% else %}
<button type="submit" class="btn btn-success" name="button">Add to cart</button>
{% endif %}
</span>
{% endif %}
</form>
my jquery and ajax:
<script type="text/javascript">
$(document).ready(function(){
var productForm=$(".form-product-ajax")
productForm.submit(function(event){
event.preventDefault();
var thisForm=$(this)
var actionEndpoint=thisForm.attr("action");
var httpMethod=thisForm.attr("method");
var formData=thisForm.serialize();
$.ajax({
url:actionEndpoint,
method:httpMethod,
data:formData,
type : 'POST',
success: function(data){
var submitSpan = thisForm.find(".submit-span")
if(data.added){
submitSpan.html("<button type="submit" class="btn btn-danger" name="button">Remove?</button>")
}else{
submitSpan.html("<button type="submit" class="btn btn-success" name="button">Add to cart</button>")
}
},
error: function(errorData){
}
})
})
})
</script>
Here is my views.py's function:
def cart_update(request):
#print(request.POST)
product_id=request.POST.get('product_id')
if product_id is not None:
try:
product_obj=Product.objects.get(id=product_id)
except Product.DoesNotExist:
print("Produuct does not exists")
return redirect("cart:home")
cart_obj,new_obj=Cart.objects.new_or_get(request)
if product_obj in cart_obj.products.all():
cart_obj.products.remove(product_obj)
added=False
else:
cart_obj.products.add(product_obj)
added=True
request.session['cart_items']=cart_obj.products.count()
if request.is_ajax():
print("Ajax request")
json_data={
"added": added,
"removed": not added,
}
return JsonResponse(json_data)
#return redirect(product_obj.get_absolute_url())
return redirect("carts:home")
jquery and ajax version:
{% load static %}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
I can't figure out why event.preventDefault(); not working whenever I add $.ajax in my project.If I comment it out event.preventDefault(); seems fine.After all ajax is not working on my project.
According to django 3.1 release notes:
The HttpRequest.is_ajax() method is deprecated as it relied on a jQuery-specific way of signifying AJAX calls, while current usage tends to use the JavaScript Fetch API. Depending on your use case, you can either write your own AJAX detection method, or use the new HttpRequest.accepts() method if your code depends on the client Accept HTTP header.
If you are writing your own AJAX detection method, request.is_ajax() can be reproduced exactly as request.headers.get('x-requested-with') == 'XMLHttpRequest'.
I find out the exact problem in this code.There the content of submitSpan.html below the if condition should be single quoted.
submitSpan.html('<button type="submit" class="btn btn-danger" name="button">Remove?</button>')
That's why console showed me this error:
(index):138 Uncaught SyntaxError: missing ) after argument list
I have a function that currently runs whenever the user clicks/tabs out of the employee_number field. I would like it to run whenever the length of the numbers entered is equal to 6, without having to leave the field, since when I try using the tab, it conflicts with loading the next field which is a drop-down that is part of the function ran.
I tried by running it using .change and putting the constraint within the function, but it did not work and I don't know what else to try.
enter_exit.html
{% extends "base.html" %}
{% load core_tags staticfiles %}
{% block main %}
<form id="warehouseForm" action="" method="POST" data-employee-activity-lookup-url="{% url 'operations:employee_activity_search' %}" novalidate >
{% csrf_token %}
<div>
<div>
<div id="employee-name" style="margin-bottom: 10px"> </div>
<label>Employee #</label>
{{ form.employee_number }}
</div>
<div=>
<label>Work Area</label>
{{ form.work_area }}
</div>
<div style="display: none" id="my-hidden-div">
<label>Station</label>
{{ form.station_number }}
</div>
</div>
<div>
<div>
<button>Enter Area</button>
<button>Exit Area</button>
</div>
</div>
</form>
<script>
// Grab the employee name and their current active work log (if any)
$(document).on('blur', "#{{ form.employee_number.id_for_label }}", function(){
var url = $("#warehouseForm").attr('data-employee-activity-lookup-url');
var employeeId = $(this).val();
# ... more fields ...
if (employeeId !== "") {
# .. Rest of function ...
})
</script>
{% endblock main %}
Instead of using on blur have you tried using .keyup or .keydown?
Here's a simple version of it working in CodePen:
$("#test1").keydown(()=>{
if($("#test1").val().length>6)
console.log('6+');
})
https://codepen.io/orunnals/pen/JjoRGLX
I'm working on a website on which users can comment something below the posts, running on Python & Django.
As soon as a user comments something, then I'm updating comments without refreshing the web-page. Here's the code,
In views.py
postType1 = sorted(Posts.objects.filter( . . . ), key=lambda x: random.random())
postType2= Posts.objects.filter( . . . )
In template,
// BLOCK - 1
{% for post in postType1 %}
<p>{{ post }}</p>
<div class="comm_update" action="{% url 'comment:create' post.id %}">
<form class="comm_form" action="{% url 'comment:create' post.id %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<textarea id="id_comment"></textarea><br /><br />
<button type="submit">Submit</button>
</form>
</div>
{% endfor %}
<hr />
// BLOCK - 2
{% for post in postType2 %}
<p>{{ post }}</p>
<div class="comm_update" action="{% url 'comment:create' post.id %}">
<form class="comm_form" action="{% url 'comment:create' post.id %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<textarea name="comment_text" id="id_comment"></textarea><br />
<button type="submit">Submit</button>
</form>
</div>
{% endfor %}
Auto updating comments without refreshing webpage,
$(document).on("submit", ".comm_form", function(t) {
t.preventDefault();
var o = $(this),
e = $.post(o.attr("action"), o.serialize()),
n = o.attr("action");
e.done(function(t) {
var e = $(t).find(".comm_update[action='" + n + "']");
o.closest(".comm_update").html(e), o[0].reset()
})
});
On localhost everything is working fine.
*But on live server the first block BLOCK - 1 is not updating the comments, instead when user presses submit entire comment section disappears.
How can we fix this issue?
Thank You!
i am trying to implement the datepicker using the django bootstrap datepicker widget, but the datepicker is not showing on the webpage ("welcome.html)
i have passed the form to the views and called the form in the webpage
any help will be appreciated
forms.py
class DateForm(forms.Form):
todo = forms.CharField(
widget=forms.TextInput(attrs={"class":"form-control"}))
date_1=forms.DateField(widget=DatePicker(
options={"format": "mm/dd/yyyy",
"autoclose": True }))
def cleandate(self):
c_date=self.cleaned_data['date_1']
if c_date < datetime.date.today():
raise ValidationError(_('date entered has passed'))
elif c_date > datetime.date.today():
return date_1
def itamdate(self):
date_check=calendar.setfirstweekday(calendar.SUNDAY)
if c_date:
if date_1==date_check:
pass
elif date_1!=date_check:
raise ValidationError('The Market will not hold today')
for days in list(range(0,32)):
for months in list(range(0,13)):
for years in list(range(2005,2108)):
continue
views.py
def imarket(request):
#CREATES A FORM INSTANCE AND POPULATES USING DATE ENTERED BY THE USER
if request.method=='POST':
form = DateForm(request.POST or None)
#checks validity of the form
if form.is_valid():
itamdate=form.cleaned_data['date_1']
return HttpResponseRedirect(reverse('welcome.html'))
return render(request, 'welcome.html', {'form':form})
welcome.html
{% extends 'base.html' %}
{% load bootstrap %}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="//cdn.bootcss.com/bootstrap-datetimepicker/4.17.44/js/bootstrap-datetimepicker.min.js"></script>
{% block content %}
<title>welcome</title>
<form action = "{% url "imarket"}" method = "POST" role="form">
{% csrf_token %}
<table>
{{form|bootstrap_horizontal}}
</table>
<div class = "form-group">
<input type ="submit" value= "CHECK" class="form control"/>
</div>
</form>
{% endblock %}
The bootstrap datepicker wasn't working , so i added the jquery datepicker to directly to my forms. py using this answer
my updated forms.py
class DateForm(forms.Form):
todo = forms.CharField(
widget=forms.TextInput(attrs={"class":"form-control"}))
date_1=forms.DateField(widget=forms.DateInput(attrs={'class':'datepicker'}))
my updated welcome.html
{% extends 'base.html' %}
{% load bootstrap %}
{% block content %}
<title>welcome</title>
<form action = "{% url "imarket"}" method = "POST" role="form">
{% csrf_token %}
<table>
{{form|bootstrap}}
<script>
$(document).ready(function() {
$('.datepicker').datepicker();
});
</script>
</table>
<div class = "form-group">
<input type ="submit" value= "CHECK" class="form control"/>
</div>
</form>
{% endblock %}
datepicker should be initialized in the html page.
if you are using bootstrap download datepicker from Datetimepicker for Bootstrap 4
then
in the head section include
font awesome css
boostrap4 css
bootstrap-datetimepicker.min.css
in the body section include
moment.min.js
bootstrap.min.js
bootstrap-datetimepicker.min.js
define your form
from django import forms
class DateRangeForm(forms.Form):
start_date = forms.DateTimeField(required=True)
end_date = forms.DateTimeField(required=True)
in the template render the form
<form action="/your-name/" method="post">
{% csrf_token %}
{{ dt_range_form }}
<input class="btn btn-primary btn-sm" type="submit" value="Refresh">
</form>
in the script section add
$("#id_start_date").datetimepicker();
And here you have your datetimepicker! For me Time icon is still not showing up! Need to debug it.
I'm trying to create my first ajax function in Django.
I want to change my code using JQuery, the idea is pretty simple:
User type a subject name and this name is displayed in subject-list below the form,
The problem is I don't really know what to type in JQuery function.
JQuery:
function create_subject() {
$("input").focus(function(){
var subject = $(this).val();
$(".btn-create").click(function(){
/* What I need to write in here */
});
});
}
In HTML "subjects" refer to database.
HTML
<div id="subjects-list">
{% if user.username %}
<ul>
{% if subjects %}
<form method="post" action=".">{% csrf_token %}
{% for subject in subjects %}
-------- TYPED TEXT SHOULD BE HERE --------> <li>{{ subject.name }}</li>
{% endfor %}
</form>
{% else %}
<p>No Subjects for this user</p>
{% endif %}
</ul>
{% else %}
You are in else
{% endif %}
</div>
That's how HTML looks in "View Page Source"
<div id="create-subject">
<form method="post" action="."> <div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='cfbd1893742c3ab9936bacaae9653051' /></div>
<p><label for="id_name">Subject Name:</label> <input id="id_name" type="text" name="name" size="9" /></p>
<input type="button" name="subject-create-b" value="Create Subject" class="btn-create"/>
</form>
</div>
<div id="subjects-list">
<ul>
<form method="post" action="."><div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='cfbd1893742c3ab9936bacaae9653051' /></div>
<li>Math 140<span id="subject-link"></span></li>
</form>
</ul>
</div>
</div>
And that's my form
forms.py
class SubjectCreationForm(forms.Form):
name = forms.CharField(label="Subject Name", widget=forms.TextInput(attrs={'size':9}))
class Meta:
exclude = ('created_by', 'created_time', 'num_of_followers', 'vote')
def clean_name(self):
name = self.cleaned_data['name']
if len(name)>1:
return name
else:
raise forms.ValidationError("Subject name should be longer")
In order to do what (I think) you want to do which is some basic AJAX using Django as your backend, you'll need the following:
A view which returns the data you want to load
There are a number of ways you can represent the data, but to keep it simple, I'll use HTML.
Javascript to load that view (using JQuery if you like)
Your code might look like this for the first part:
urls.py:
...
(r'^get-subjects/$', 'yourapp.views.get_subjects'),
...
views.py:
...
def get_subjects(request):
subjects = # code to fetch your subjects.
return render_to_response('subjects_template.html', {'subjects': subjects})
...
subjects_template.html:
{% for subject in subjects %}
<li>{{ subject.name }}</li>
{% endfor %}
For the second part, it might look like this:
main_template.html:
...
<ul id="subjects-list"></ul>
<script>
function loadSubjects() {
$.ajax({
url: "/get-subjects",
success: function (data) {
$("#subjects-list").html(data);
}
});
}
</script>
...
[1] render_to_response()
[2] jQuery.ajax()
This will get you most the way there. When you want to reload the list, you call the loadSubjects() function.
As far as creating the subjects go, that is a different thing. What you'll want to look into is how to do an HTML form submission without leaving the page. There are plenty of tools and libraries to do that stuff with a nice api. If you want to stick with JQuery, you might consider this plugin for a nicer api.
function create_subject() {
$("input").focus(function(){
var subject = $(this).val();
$(".btn-create").click(function(){
$('#subjects-list').append(subject);
});
});
}
that said, you probably don't want to assign the click handler every time the input is focused. i'd move that out of the focus handler.