date picker for form field , placed in an template was not supporting.. Here's the code
forms.py:
class GuestFacultyCourseOfferForm(BaseGuestFacultyCourseOfferForm):
teaching_mode = forms.ModelChoiceField(queryset=TeachingMode.objects.all())
location_mode = forms.ModelChoiceField(queryset=LocationMode.objects.all())
# class_start_date = forms.DateField(required=True,)
classstartdate = forms.DateField(label='Date',required=True)
template code:
This is the script code for date picker which was given for form field "classstartdate".
<script type="text/javascript" src="{% url 'admin:jsi18n' %}"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src="{% static 'admin/js/jquery-new.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/jquery-ui.min.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/jquery-validate.js' %}"></script>
<script>
$(document).ready(function() {
$( "#id_classstartdate" ).datepicker({
changeMonth: true,
changeYear: true,
minDate:0,
buttonImage: "{% static "admin/img/icon_calendar.gif" %}",
buttonImageOnly: true,
buttonText: "Select date",
showOn:"both",
});
});
</script>
--> this is body code where i have given form fields in table:
<form method="post">
{% csrf_token %}
<table id="formset" class="form">
<thead>
<tr>
<th>TEACHING MODE</th>
<th>LOCATION MODE</th>
<th>CLASS START DATE</th>
</tr>
</thead>
{% for form in formset_assign_faculty.forms %}
<tr class="{% cycle row1,row2 %}">
<td>{{ form.teaching_mode}} {{ form.teaching_mode.errors.as_ul }}</td>
<td>{{ form.location_mode}} {{ form.location_mode.errors.as_ul }}</td>
<td>{{ form.classstartdate}} {{ form.location_mode.errors.as_ul }}</td>
</tr>
{% endfor %}
</table>
</form>
If you are using formset the input id of each form is different, it is formed like "id_" + form prefix + field name.
So, try to change $("#id_classstartdate") where you initiate datepicker to $("[id^=id_][id$=classstartdate]"). This will find inputs which start with "id_" and end with form field name classtartdate.
Related
here i send my details
how can i stop this for example if i run http://127.0.0.1:7000/search_acctable/?txt=Kalpesh but if now i again run my code this is run like http://127.0.0.1:7000/search_acctable/?txt=Kalpesh/search_acctable/?txt=any in django how can i solve this
i need help to solve this problem
views.py
def s_index(request):
current_url = request.build_absolute_uri()
#print(current_url)
src = request.POST.get('txt_search')
#if request.POST['btn_clear']:
# return HttpResponseRedirect(request.META.get('HTTP_REFERER')) # return to previous page
if request.POST['btn_search']:
rec=accmaster.objects.filter(Q(acc_name__contains=src) | Q(acc_city__contains=src)| Q(acc_op__contains=src) ).values() # for filter with and conition onyl put comma if want or condition use pipe sign and Q
if rec.exists():
rec=accmaster.objects.filter(Q(acc_name__contains=src)| Q(acc_city__contains=src)| Q(acc_op__contains=src)).values()
grp_city=accmaster.objects.filter( Q(acc_name__contains=src) | Q(acc_city__contains=src)| Q(acc_op__contains=src)).values('acc_city').annotate(Sum('acc_op')).order_by('acc_city')
template=loader.get_template('index.html')
output=accmaster.objects.filter(Q(acc_name__contains=src)| Q(acc_city__contains=src)| Q(acc_op__contains=src)).values().aggregate(Sum('acc_op'))
context ={
'rec':rec,
'output':output['acc_op__sum'],
'grp_city':grp_city,
}
return HttpResponse(template.render(context,request))
else :
return HttpResponseRedirect(request.META.get('HTTP_REFERER')) # return to previous page
urls.py
from django.urls import path
from . import views
urlpatterns=[
path('',views.index,name='index'),
path('addacc/',views.add,name='addacc'),
path('addacc/addrecord/',views.addrecord,name='addrecord') ,
path('delete/<int:id>',views.delete,name='delete') ,
path('update/<int:id>',views.update,name='update'),
path('update/updaterecord/<int:id>',views.updaterecord,name='updaterecord'),
path('index/',views.s_index,name='s_index'),
#path('',views.form_view,name='mform')
]
index.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function printreport(){
//var divtoprint=document.getElementById("maindiv");
var printcontext=document.getElementById("maindiv").innerHTML;
var originalcontext=document.body.innerHTML;
var nwin=window.open("");
nwin.document.open();
nwin.document.write('<html><head><link rel="stylesheet" media="print" href="{% static 'mystyleprint.css' %}" ></head><body>');
nwin.document.write(printcontext);
nwin.document.write("</body></html>");
//document.write(printcontext);
//document.body.innerHTML=printcontext;
//printWindow.document.write(divtoprint);
nwin.print();
nwin.document.close();
nwin.close();
}
</script>
<link rel="stylesheet" href="{% static 'mystyle.css' %}" >
<link rel="stylesheet" href="{% static 'mystyleprint.css' %}" media="print"> <!-- make seprate css for print document and make media print-->
</head>
<body >
<form action="index/" method="post" >
{% csrf_token %}
<div>
<button type="button">Add Account</button>
<label>Search :</label> <input id="txt_search" name="txt_search" autocomplete="off">
<input type="submit" id="btn_search" name="btn_search" value="Search" onclick="myfunction()">
<input type="button" id="btn_clear" name="btn_clear" value="clear"" onclick="history.back()">
<input type="button" name="btn_print" value="Print" onclick="printreport()">
</div>
<br>
<div id="maindiv">
<table id="maintable">
{% with no="s" %}
<h1> Account List </h1>
<tr>
<th> Sr.No </th>
<th> Name </th>
<th> City </th>
<th> Opening Balance </th>
<th id="thedit"> Edit </th>
<th id="thdelete"> Delete </th>
</tr>
{% for y in grp_city %}
<tr>
<td id="tdcity" colspan=4 style="color:magenta"> {{ y.acc_city }}</td>
{% for x in rec %}
{% if x.acc_city == y.acc_city %}
<tr>
<td style="width:4%" id="srno"></td>
<td>{{ x.acc_name }}</td>
<td style="width:20%"> {{ x.acc_city}}</td>
<td align="right" style="width:10%"> {{ x.acc_op}}</td>
<td style="width:4%" id="redit"> <img src="{% static 'icon/update.png' %}"></td>
<td style="width:4%" id="rdelete"> </td>
</tr>
{% endif %}
{% endfor %}
<td colspan=4 align="right" style="color:magenta; font-size:18px;" >Total: {{ y.acc_op__sum|floatformat:2 }} </td>
<td colspan=2 id="nodisp"> </td>
</tr>
{% endfor %}
<tr>
<td colspan=4 align="right" style="color:red; font-size:20px">Total : {{output|floatformat:2}} </td>
</tr>
</table>
</div>
<p>
</p>
{% endwith %}
</form>
</body>
</html>
i don't know to how to handle it i am new to django
I am continuing to learn Django as a newbie.....I would like some direction in relation to 1 search query against two tables that hold the same headers such as customer names.
So table 1 is customer names from 2022 and table 2 is customer names from 2021.
I can create the models / admin and URL and set the project up.
How do I create a query to search both tables at the same time and display the result?
View.py
def index(request,):
q = request.GET.get('q')
if q:
#this is what is searched against.....ie the columns in our model.py
vector = SearchVector('name')
#This is the value the user is searching for:
query = SearchQuery (q)
# customers = customer.objects.filter(name__search=q)
# customers = customer.objects.annotate(search=vector).filter(search=query)
customers = customer1.objects.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.001).order_by('-rank')
else:
customers = None
context = {'customers': customers}
return render(request, 'index.html', context)
Index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>GAEN</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
</head>
<body>
{% include 'navbar.html' %}
<div class="container">
{% block content %}
<br><br><br><br>
<form>
<div class="mb-3">
<label for="Search Query" class="form-label ">
<h3>db Search Query</h3>
</label>
<br><br>
<input type="text" class="form-control" aria-describedby="#" name="q">
<br><br>
<button type="submit" class="btn btn-primary ">Submit</button>
<button type="submit" class="btn btn-danger">Reset</button>
</div>
</form>
{% if customers %}
<br>
<h3><mark>Results:</mark> {{ customer | length }}</h3>
<br><br>
{% for customer in customers %}
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Search Result</th>
<th scope="col">name</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>{{ customer.name }}</td>
</tr>
</tbody>
</table>
Rank: {{ customer.rank }}
<br><br><br>
{% endfor %}
{% endif %}
{% endblock %}
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/js/bootstrap.bundle.min.js"
integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2"
crossorigin="anonymous"></script>
Django-filter can do it easily!
I created an inline relation between Reader and Book models.
I imported the formset in my template successfully but I can not create a new Book form by clicking a link related to my addtext attribute in the below script. In otherwords, for one Reader I want to be able to create more than one Book form by clicking a link.
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'jquery.formset.js' %}"></script>
<script type="text/javascript">
$('table.book tr.formset_row').formset({
addText: 'Add new Book',
deleteText: 'Delete',
prefix: 'reader_book_set',
animateForms: true
});
</script>
The whole template is this:
{% extends 'base.html' %}
{% load bootstrap3 %}
{% load static %}
<!-- Latest compiled and minified JavaScript -->
{% block content %}
<div class="col-md-12 text-center">
<h2>Create / Edit Reader </h2>
</div>
<hr>
<form class="well" method="post" action="">
{% csrf_token %}
{% bootstrap_form form %}
<table class="table book">
{{ formset.management_form }}
{% for form in formset.forms %}
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tr class="{% cycle row1 row2 %} formset_row">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'jquery.formset.js' %}"></script>
<script type="text/javascript">
$('table.book tr.formset_row').formset({
addText: 'Add new Book',
deleteText: 'Delete',
prefix: 'reader_book_set',
animateForms: true
});
</script>
{% buttons %}
<button type="submit" class="btn btn-primary">
Submit
</button>
{% endbuttons %}
</form>
<hr>
{{ form.media }}
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/forms.css' %}"/>
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/base.css' %}"/>
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/widgets.css' %}"/>
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="/static/admin/js/core.js"></script>
<script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js"></script>
<script type="text/javascript" src="/static/admin/js/vendor/jquery/jquery.min.js"></script>
<script type="text/javascript" src="/static/admin/js/jquery.init.js"></script>
<script type="text/javascript" src="/static/admin/js/actions.min.js"></script>
<script type="text/javascript" src="/static/admin/js/calendar.js"></script>
<script type="text/javascript" src="/static/admin/js/admin/DateTimeShortcuts.js"></script>
{% endblock %}
Here is my view:
class ReaderBookCreateView(LoginRequiredMixin, CreateView):
model = Reader
fields = '__all__'
template_name='test/test.html'
def get_context_data(self, **kwargs):
data = super(ReaderBookCreateView, self).get_context_data(**kwargs)
if self.request.POST:
data['formset'] = BookFormSet(self.request.POST)#bound the formset with data
else:
data['formset'] = BookFormSet()#empty formset
return data
def form_valid(self, form):
context = self.get_context_data()
formset = context['formset']
with transaction.atomic():
self.object = form.save()
if formset.is_valid():
formset.instance = self.object
formset.save()
return super(ReaderBookCreateView, self).form_valid(form)
def get_success_url(self, **kwargs):
return reverse('client_list')
Here is how it looks. I would like to have a link Add new Book above the submit button for creation of the new Book form for the current reader.
Any help will be appreciated.
It was as usual in these situations a javascript issue. I solve it.
My project could not found the path for jquery.formset.js file.
Use F12 always when you trying to debug javascript.
I have my own HTML page "stat.html" which shows some graphs, this is hyperlinked from a custom index page that I made using this method answer3.
My current admin/custom_admin.html page looks like this
{% extends "admin/index.html" %}
{% block content %}
{{block.super}}
<div class="module">
<table style="width:100%">
<caption>
<a class="section">Statistics </a>
</caption>
<tbody>
<th scope="row">
Stats Page
</th>
</tbody>
</table>
</div>
{% endblock %}
The link /myapp/statpage is link to a static html page, it is showing two google charts in it, something like this
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Stats</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script type = "text/javascript" src =
"https://www.gstatic.com/charts/loader.js"> </script>
<script type = "text/javascript"> google.charts.load('current',
{packages: ['corechart']}); </script>
<script src="{% static "v_stats.js" %}"></script>
</head>
<body>
<div id="container" style="width:80%; height:35vw; margin:"auto";"></div>
<div id="container1" style="width:80%; height:35vw; margin:"auto";"></div>
</body>
</html>
How do I just inherit the Django admin header in this stat.html page and have my own title, some links to static js pages and some content in it?
from myproject.admin import admin_site
admin.site.site_header = 'My administration'
You may now wish to use this elsewhere in your site, by inserting it as context into your templates.
Has anyone tried to use DataTables with Django? I could not seem to get it to work, I had everything in the static files, etc..
Once I try and use datatables, I lose all the template styling and it just goes back to a default table.
EDIT There is not error when I load the page, all the data shows up just no template or datatables effects loading
This is the code:
{% load static %}
{% block content %}
<script src="{% static "assets/js/jquery.datatables.js" %}" type="text/javascript"> </script>
<script src="{% static "assets/js/jquery.js" %}" type="text/javascript"></script>
<link rel="stylesheet" href="{% static "assets/css/jquery.dataTables.css" %}" type="text/css"/>
<h1>Full list of supported Golf Courses:</h1>
<br>
<script type="text/javascript" charset="utf-8">
$(document).ready( function () {
$('#courses').dataTable();
} );
</script>
<table id="courses" class="display">
<tr>
<th>Golf Course</th>
<th>Front 9</th>
<th>Back 9</th>
<th>Total Par</th>
</tr>
{% for course_name, par_front_9, par_back_9, total_par in data %}
<tr>
<td>{{ course_name }}</td>
<td>{{ par_front_9 }}</td>
<td>{{ par_back_9 }}</td>
<td>{{ total_par }}</td>
</tr>
{% endfor %}
</table>
</div>
{% endblock %}
Got it working, noticed that the code worked when removing {% extend "base.html" %}. Fixed it by using {% include "base.html" %}