I have a form that I want to submit date as mm/yyyy.
class Add_Serv(forms.Form):
month_add = forms.ChoiceField(required=True, choices=['01','02'])
year_add = forms.ChoiceField(required=True,
choices=[(x, x) for x in xrange(date.today().year - 1, date.today().year + 1)])
When my month prints out in form, it's only one digit integer 1 instead of 01. It doesn't sound like a big deal but it screws up my date format when handling these dates (and also looks very ugly). Is there any way to keep that zero before the number?
add validation in form's clean method and check if the length of month field is 1 or 2.
Append 0 before if length is 1 and return value of month
Print it out using format:
print("{:02d}".format(my_number))
See Pyformat for more formatting tips
use jquery library
You need only one field.
forms.py
class FormA(forms.Form):
fecha = forms.DateField(input_formats=['%m/%Y'])
views.py
def formulario(request):
if request.method == "POST":
form = FormA(request.POST)
if form.is_valid:
# action
else:
form = FormA()
return render(request,"add.html",{'form':form})
Your template
I add bootstrap css library and django-bootstrap-from
<div class="row">
<div class="col-lg-8">
<form id="form" action="" method="POST">
{{form|bootstrap_horizontal}}
{%csrf_token%}
<p align="right"><button id="enviar" type= 'submit' class="btn btn-success"> Guardar</button>
<button type= "reset" class="btn btn-warning"> Limpiar</button></p>
</form>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">
<script type="text/javascript">
$(function() {
$('#id_fecha').datepicker( {
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'mm/yy',
onClose: function(dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
}
});
});
</script>
<style>
.ui-datepicker-calendar {
display: none;
}
</style>
The result
http://prntscr.com/7qd01v
Related
I want to send {{order.id}}, but getting error like pictuce in bellow, please helping me to solve problem
Image Error
Views.py:
def Detail_pem(request, idor):
print(idor)
return render(request, 'store/detail.html' )
pemby.html:
<!-- <button data-product="{{order.id}}" data-act="{{order.name}}" class="btn btn-warning id_order btntam" >Detail</button> -->
<button data-product="{{order.id}}" data-act="{{order.name}}" class="btn btn-warning id_order btntam" >Detail</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- <script type="text/JavaScript" src="{% static 'js/pem.js' %}"></script> -->
<script>
var id_order = document.getElementsByClassName('id_order')
for (i = 0; i < id_order.length; i++) {
id_order[i].addEventListener('click', function(){
var orid = this.dataset.product
var ornm = this.dataset.act
console.log('orid :', orid)
console.log('ornm :', ornm)
window.location.href = "{% url 'Detail_pem' %}"
})
}
urls.py:
path('Detail_pem/<idor>', Detail_pem, name='Detail_pem'),
You are redirecting through
window.location.href = "{% url 'Detail_pem' %}" without a variable.
But in your urls.py you are passing idor variable.
It should be: window.location.href = "{% url 'Detail_pem' order.id } %}".
And your urls.py change to this:
int:id
#if you are passing integer
path('Detail_pem/<int:id>', Detail_pem, name='Detail_pem'),
#or if you are passing string
path('Detail_pem/<str:id>', Detail_pem, name='Detail_pem'),
I am using full calendar in my in my Django project and I was wondering how I would get the model data to load as an event within the calendar. The issue is whenever I try to load the template into my code it loads up a white page with text in JSON format.
I was wondering if it was possible to get by this.
This is how my model looks like:
class CalenderEvent(models.Model):
event_name = models.CharField(max_length = 30)
start_date = models.DateTimeField(null=True,blank=True)
end_date = models.DateTimeField(null=True,blank=True)
event_description = models.TextField()
def __str__(self):
return self.event_name
This is how my view looks like:
def calender(request):
events = CalenderEvent.objects.all()
if request.method == 'GET':
form = ContactToAddEventForm()
event_arr = []
for i in events:
event_sub_arr = {}
event_sub_arr['title'] = i.event_name
start_date = datetime.datetime.strptime(str(i.start_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d")
end_date = datetime.datetime.strptime(str(i.end_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d")
event_sub_arr['start'] = start_date
event_sub_arr['end'] = end_date
event_arr.append(event_sub_arr)
return HttpResponse(json.dumps(event_arr))
context = {
"events" : events
}
return render(request, 'calender.htm', {'form': form}, context)
This is how my template looks like:
<link rel="stylesheet" href="{% static "fullcalender/daygrid/main.css" %}" >
<link rel="stylesheet" href="{% static "fullcalender/timegrid/main.css" %}" >
<link rel="stylesheet" href="{% static "fullcalender/core/main.css" %}" >
<script rel="stylesheet" href="{% static "fullcalender/core/main.js" %}" ></script>
<script src="{% static "fullcalender/core/main.js" %}"></script>
<script src="{% static "fullcalender/daygrid/main.js" %}"></script>
<script src="{% static "fullcalender/timegrid/main.js" %}"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'timeGrid' ],
defaultView: 'timeGridWeek',
events: [
{% for i in events %}
{
title: "{{ i.event_name}}",
start: '{{ i.start_date|date:"Y-m-d" }}',
end: '{{ i.end_date|date:"Y-m-d" }}',
},
{% endfor %}
]
});
calendar.render();
});
</script>
<section>
<div class="container">
<div id = "calendar"></div>
</div>
</section>
I was looking at this stack overflow answer:
FullCalendar in Django
I am using django to create a webpage and this is the first time I am doing so. I am trying to fetch the value of a variable from .py file at an interval of 5 seconds. Below is the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Like Post App</title>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>
<body>
<div class = "display-3 color-red"><center>DataFlair AJAX Tutorial<br>Post APP</center></div>
{% for post in posts %}
<div class = 'container jumbotron'>
<h3 class="display-5">{{ forloop.counter }}. {{ post.post_heading }}</h3>
<p class="lead">{{ post.post_text }} </p>
<p>
<div type="text/css" class = "container">Author : {{ post.post_author }}</div>
<a class="likebutton btn btn-primary btn-lg" id="like{{ post.id }}" data-catid="{{ post.id }}">Like({{ post.like_ref.counter }})</a> </p> <p id="message{{post.id}}">
</p>
</div>
{% endfor %}
<script type="text/javascript">
setInterval(function() {
getvalue(); // Do something every 5 seconds
}, 5000);
getvalue();
function getvalue(){
var id;
id = $(this).attr("data-catid");
$.ajax(
{
type:"GET",
url: "like",
data:{
post_id: id
},
success: function( data )
{
$( '#like'+ id ).text("Like(" + data +")");
var i=parseInt(data);
console.log("Value= "+i);
}
}
)
}
</script>
</body>
</html>
Below is the views.py code:
import json
from django.shortcuts import render
from .models import Post, Like
from django.http import HttpResponse
# Create your views here.
#DataFlair #AJAX_tutorial
def index(request):
posts = Post.objects.all()
return render(request, 'post/index.html', { 'posts': posts })
def like(request):
if request.method == 'GET':
post_id = request.GET['post_id']
likedpost = Post.objects.get(id = post_id )
m = Like.objects.filter( post=likedpost ).first()
m.counter +=1
m.save()
value1= int(m.counter)
#data1= {'cmd': 'success', 'ctr': str(m.counter) }
return HttpResponse(value1)
#return HttpResponse(json.dumps(data1))
else:
return HttpResponse("unsuccesful")
I keep getting the following errors:
1) GET http://localhost:8000/ajax/like/ 500 (Internal Server Error)
2) GET http://localhost:8000/favicon.ico 404 (Not Found)
Please help.
I believe:
id = $(this).attr("data-catid");
is not pointing to the button... maybe you should try:
id = $(".likebutton").attr("data-catid");
Hello guys i have a html program in which i'm Moving the Items from One Multi Select List To Another using jQuery which is written like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> upload </title>
</head>
<script>
$(function () {
function moveItems(origin, dest) {
$(origin).find(':selected').appendTo(dest);
}
function moveAllItems(origin, dest) {
$(origin).children().appendTo(dest);
}
$('#left').click(function () {
moveItems('#sbTwo', '#sbOne');
});
$('#right').on('click', function () {
moveItems('#sbOne', '#sbTwo');
});
$('#leftall').on('click', function () {
moveAllItems('#sbTwo', '#sbOne');
});
$('#rightall').on('click', function () {
moveAllItems('#sbOne', '#sbTwo');
});
});
</script>
<body>
<div class="container">
<h1>Large Data Generation</h1>
</div>
<h2>Move Items From One List to Another</h2>
<select id="sbOne" multiple="multiple">
<option value="1">Alpha</option>
<option value="2">Beta</option>
<option value="3">Gamma</option>
<option value="4">Delta</option>
<option value="5">Epsilon</option>
</select>
<select id="sbTwo" multiple="multiple">
<option value="6">Zeta</option>
<option value="7">Eta</option>
</select>
<br />
<input type="button" id="left" value="<" />
<input type="button" id="right" value=">" />
<input type="button" id="leftall" value="<<" />
<input type="button" id="rightall" value=">>" />
</body>
</html>
In this i'm able to move the items from one multi select to another but i want don't want to Hard code the items names i want it to read through the csv file and take the header columns of the csv file
This is the csv file:
with open("Data_Large2.csv", "rt") as f:
reader = csv.reader(f)
HeaderName = next(reader)
print("HeaderName-",HeaderName)
output:
['Asset_Id',
'Asset Family',
'Asset Name',
'Location',
'Asset Component']
This is the Header column name which I want to populate in place of Alpha, Beta..not there values which I have taken Is there any way to get the headers of the column from CSV file in jquery please help me ..thnx in advance
I don't know what exactly you are searching for but i assume that you are reading a csv file from web and you can also select more than one csv file For that i have made some change in your program : Note: Here i have change the "sbone" to "sourceHeaderFields" and "sbTwo" to "targetHeaderFields"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> upload </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link href="https://bootswatch.com/4/solar/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>
<script>
$(function () {
function moveItems(origin, dest) {
$(origin).find(':selected').appendTo(dest);
}
function moveAllItems(origin, dest) {
$(origin).children().appendTo(dest);
}
$('#left').click(function () {
moveItems('#targetHeaderFields', '#sourceHeaderFields');
});
$('#right').on('click', function () {
moveItems('#sourceHeaderFields', '#targetHeaderFields');
});
$('#leftall').on('click', function () {
moveAllItems('#targetHeaderFields', '#sourceHeaderFields');
});
$('#rightall').on('click', function () {
moveAllItems('#sourceHeaderFields', '#targetHeaderFields');
});
$('#populateHeaderFields').on('click', function () {
alert("Inside populate list");
var files = ('#source_fileName').files;
alert("Files Count - "+ files);
});
$('#upload-form').on('change', function(evt) {
var filesCount = evt.target.files.length;
for (i = 0; i < filesCount; i++) {
var file = evt.target.files[i];
if (file) {
var reader = new FileReader();
// Read our file to an ArrayBuffer
reader.readAsArrayBuffer(file);
// Handler for onloadend event. Triggered each time the reading operation is completed (success or failure)
reader.onloadend = function (evt) {
// Get the Array Buffer
var data = evt.target.result;
// Grab our byte length
var byteLength = data.byteLength;
// Convert to conventional array, so we can iterate though it
var ui8a = new Uint8Array(data, 0);
// Used to store each character that makes up CSV header
var headerString = '';
// Iterate through each character in our Array
for (var i = 0; i < byteLength; i++) {
// Get the character for the current iteration
var char = String.fromCharCode(ui8a[i]);
// Check if the char is a new line
if (char.match(/[^\r\n]+/g) !== null) {
// Not a new line so lets append it to our header string and keep processing
headerString += char;
} else {
// We found a new line character, stop processing
break;
}
}
//Iterate through the list and populate the select element..
$.each(headerString.split(","), function(i,e){
$("#sourceHeaderFields").append($("<option>", {
text: e,
value: e
}));
});
console.log(headerString);
console.log("Next Read");
};
} else {
alert("Failed to load file");
}
}
});
});
</script>
<body>
<div class="container">
<h1>Large Data Generation</h1>
</div>
<form id = "upload-form" action="{{ url_for('upload') }}" method="POST" enctype="multipart/form-data">
<div id="file-selector">
<p>
<strong>Input File: </strong>
<input id="source_fileName" type="file" name="source_fileName" accept="csv/*" multiple >
</p>
</div>
<h2>Move Items From One List to Another</h2>
<select id="sourceHeaderFields" multiple="multiple">
</select>
<select id="targetHeaderFields" multiple="multiple">
</select>
<br />
<input type="button" id="left" value="<" />
<input type="button" id="right" value=">" />
<input type="button" id="leftall" value="<<" />
<input type="button" id="rightall" value=">>" />
</body>
</html>
I think this will help you get what you need
I am trying to implement "Upload Progress Bar" in Django.
Following is my code in the template file:
{% extends "index_base.html" %}
{% block content %}
<script src="/media/js/functions.js" type="text/javascript"></script>
<script src="/media/js/jquery.js" type="text/javascript"> </script>
<script type="text/javascript">
var xhrObject1;
var xhrObject2;
function createXMLHttpObject()
{
var xhrObject; // The variable that makes Ajax possible!
try
{
xhrObject = new XMLHttpRequest();
}
catch (e)
{
try{
xhrObject = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e){
try {
xhrObject = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xhrObject = null;
}
}
}
return xhrObject;
}
function ajaxFunction()
{
xhrObject1 = createXMLHttpObject();
if (xhrObject1 == null)
{
alert("Your browser does not support ajax.");
return;
}
xhrObject1.onreadystatechange = function(){
if(xhrObject1.readyState == 4){
document.getElementById("targetDiv").innerHTML = xhrObject1.responseText;
}
else
{
xhrObject2 = createXMLHttpObject();
xhrObject2.onreadystatechange = function(){
if(xhrObject2.readyState == 4){
document.getElementById("targetDiv").innerHTML = xhrObject2.responseText;
}
else
{
document.getElementById("targetDiv").innerHTML = "getting progress...";
}
}
xhrObject2.open("GET", "/upload_progress.psp", true);
xhrObject2.send(null);
}
}
var arrFiles = document.getElementById('id_file');
var fileToUpload = arrFiles.files[0];
xhrObject1.open("POST", "/upload.psp/", true);
xhrObject1.send(fileToUpload);
}
function submitForm()
{
document.forms["myform"].submit();
ajaxFunction();
return false;
}
</script>
<div id="main_container">
{% include "includes/nav.html" %}
<!------- Main Contents ---------->
<div id="contents_holder">
<div id="contents">
<div id="c_banner">
<span class="main_title">Upload File</span>
</div>
<div id="targetDiv" > </div>
<div id="setting">
<form name="myform" id="myform" action="/upload.psp/" method="post" enctype="multipart/form-data">
<h2>Upload File</h2></br>
<p>{{ form.file.label_tag }} {{ form.file }}</p></br>
<input type="button" value="Upload" name="uploadButton" onclick="javascript:return submitForm();"/>
<input type="button" value="Cancel" name="cancelUploadButton" onclick ="cancelUploadClicked()"/>
<input type="hidden" value="title" name="title" id="title" />
</form>
</div>
</div>
</div>
</div>
{% endblock %}
Following are my two functions inside views.py:
#condition(etag_func=None)
def upload(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
#handle_uploaded_file(request.FILES['file'])
f = request.FILES['file']
filename = "/host_lighttpd/var/www/htdocs/satellite/static/Data/" + f.name
destination = open(filename, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
#yield chunk
request.session['uploaded'] += chunk
destination.close()
return render_to_response('uploadsuccess.html')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
def upload_progress(request):
#uploaded = request.session['uploaded']
return HttpResponse("Upload progress function...")
#return HttpResponse(uploaded)
My problem is how can I return the upload status back to the
second ajax call (GET method), so that it can be eventually updated
inside the html.
I don't know how can I return the ongoing uploading status.
Any help would be appreciated. Thanks in advance.
I recently had to do a bit of digging to find a solution for this myself.
Check out :-
http://fairviewcomputing.com/blog/2008/10/21/ajax-upload-progress-bars-jquery-django-nginx/
I have not tried the solution referenced yet, but it looks reasonable enough.
It involves registering a custom file upload class to expose the upload progress information.