Django how to chain sorting and filtering by GET request - django

When I select ordering I can't really include automatically per-page filter.
How do I make these filters "visible" to each other? What do I need include or read?
That's a small part of my view.py
if order == 'asc':
p = p.order_by('name')
elif order == 'desc':
p = p.order_by('-name')
elif order == 'price_asc':
p = p.order_by('price_netto')
elif order == 'price_desc':
p = p.order_by('-price_netto')
else:
p.order_by('name')
if limit == "12":
per_page = "12"
elif limit == "24":
per_page = "24"
elif limit == "48":
per_page = "48"
else:
from endless_pagination.settings import PER_PAGE
per_page = PER_PAGE
HTML
<select onchange="location = this.options[this.selectedIndex].value">
<option value="">--- Sortowanie ---</option>
<option rel="order" value="?order=desc">Malejąco według nazwy</option>
<option rel="order" value="?order=asc">Rosnąco według nazwy</option>
<option rel="order" value="?order=price_asc">Rosnąco według ceny</option>
<option rel="order" value="?order=price_desc">Malejąco według ceny</option>
</select>
Produktów na stronę:
<a rel="limit" href="?limit=12">12</a>, <a rel="limit" href="?limit=24">24</a>, <a rel="limit" href="?limit=48">48</a>

Why not use javascript, jquery. You need a function that will read the query string and override the item you're changing.
<select id="sort-dropdown">
<option value="">--- Sortowanie ---</option>
<option rel="order" value="desc">Malejąco według nazwy</option>
<option rel="order" value="asc">Rosnąco według nazwy</option>
<option rel="order" value="price_asc">Rosnąco według ceny</option>
<option rel="order" value="price_desc">Malejąco według ceny</option>
</select>
Produktów na stronę:
<a rel="limit" id="limit-12" href="#">12</a>, <a rel="limit" id="limit-24" href="#">24</a>, <a rel="limit" id="limit-48" href="#">48</a>
Then the javascript will look like:
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
function redirect(order, limit) {
window.location.url = "?order=" + order + "&limit=" + limit;
}
$("#sort-dropdown").change(function () {
redirect($(this).val(), getParameterByName("limit"));
});
$("#limit-12").change(function () {
redirect(getParameterByName("order"), "12");
});
$("#limit-24").change(function () {
redirect(getParameterByName("order"), "24");
});
$("#limit-48").change(function () {
redirect(getParameterByName("order"), "48");
});

Related

How to get the ID of record in another html?

why i cant get the ID of payment type, even i already print the ID in the html?
in my first html (elementary.html) I have this code
<select name="gradelevel" id="gradelevel" onchange="ChangeYearList(this.value)">
<option">-- Education Level --</option>
{% for ylvl in edulevel %}
<option value="{{ylvl.id}}">{{ylvl.Description}}</option>
{% endfor %}
</select>
<div id="txtHint" class="scale-in-center" width="100%"></div>
<script>
function ChangeYearList(str) {
var xhttp;
var x = document.getElementById("gradelevel").value;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
document.getElementById("demo").innerHTML = x;
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xhttp.open("GET", "{% url 'paymentElementary' %}?payments_ID="+str, true);
xhttp.send();
}
</script>
this is my views.py
def paymentElementary(request):
paymentsid = request.GET.get('payments_ID')
payment = ScheduleOfPayment.objects.filter(Education_Levels=paymentsid).order_by('Payment_Type').distinct('Payment_Type')
return render(request, 'accounts/paymentElementary.html', {"payment":payment})
This is my second html (paymentElementary.html)
<select id="payments" name ="payments">
<option value="0">-- Payment Type --</option>
{% for paymentschedule in payment %}
<option value="{{paymentschedule.Payment_Type.id}}">{{paymentschedule.Payment_Type.id}}. {{paymentschedule.Payment_Type}}</option>
{% endfor%}
</select>
this is what it looks like in web view
it works like a charm. but when i tried to save it into my database
id = request.POST.get('payments')
payment = PaymentType(id=id)
V_insert_data = StudentsEnrollmentRecord.objects.create(
Payment_Type=payment
)
this is the error
this is the full traceback
update view.py file in this way
def paymentElementary(request):
paymentsid = request.GET.get('payments_ID')
payment = ScheduleOfPayment.objects.get(Education_Levels=paymentsid).order_by('Payment_Type').distinct('Payment_Type')
return render(request, 'accounts/paymentElementary.html', {"payment":payment})

How to use if statments to run second function Google script

I am trying to speed up my script, right now I currently have it set up so that on a button click a custom dialog (HTML) appears asking some questions. On submit, it calls out a gs function to pull the info back as variables. Depending on the first answer I have a series of If statments that trigger. Each of them pull up a different template, make a copy, populate some cells, emails it to you, and then dumps the data into a tracker. Each of them are different so the script is rather long - is there a way to have each if statment its own function? Would this even help the speed? I am new to scripting so any feedback is appreciated. Below is the Code and HTML
function onOpen() //adds option to top row in case buttons are not working.
{
var ui = SpreadsheetApp.getUi();
ui.createMenu('Create Doc.')
.addItem('Create Tracked Document', 'addItem')
.addToUi();
}
function addItem()//starts the initiation process
{
var html = HtmlService.createTemplateFromFile('form')
.evaluate()
.setWidth(300)
.setHeight(550);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Create New Document');
}
function addNewItem(form_data)//pulls data from form
{
var ui = SpreadsheetApp.getUi();
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var n = new Date();
var now = ((n.getMonth()+1) + "/" + n.getDate() + "/" + n.getFullYear());
var doctyp = form_data.Document_Type;
var name = form_data.Name;
var title = form_data.Title;
var platform = form_data.Platform;
var area = form_data.Area;
var rota = form_data.Rotation;
var works = form_data.WorkSt;
var recipient = Session.getEffectiveUser().getEmail();
if (form_data.Document_Type == "Text2"){
var dumpfolder = DriveApp.getFolderById("12345")
var templateSheet = DriveApp.getFileById("67890");
var Newform2= templateSheet.makeCopy(title+ " "+now,dumpfolder);
var qs = SpreadsheetApp.open(Newform2);
var dropSheet = qs.getSheetByName("blank");
var URL3 = Newform2.getUrl();
dropSheet.getRange("i8").setValue(title);
dropSheet.getRange("bc5").setValue(now);
dropSheet.getRange("b5").setValue(platform);
dropSheet.getRange("p5").setValue(area);
dropSheet.getRange("x5").setValue(rota);
dropSheet.getRange("al5").setValue(works);
dropSheet.getRange("at6").setValue(name);
NewOPLPOA.setSharing(DriveApp.Access.DOMAIN,DriveApp.Permission.COMMENT);
NewOPLPOA.setOwner("ME");
sheet.appendRow([now,doctyp,name,title,platform,area,rota,works,URL3]);
GmailApp.sendEmail(recipient, title+ " has been created.", "Your document has been created." +'\n'+ "Here is the link to your copy! Link: " + URL3);
ui.alert("Email Sent", "An email has been sent with your documents link. You can also use the below link to view the document now, click ctrl C to copy. \
" + URL3, ui.ButtonSet.OK);
}
else if (form_data.Document_Type == "Text1"){
var dumpfolder = DriveApp.getFolderById("abcd")
var templateSheet = DriveApp.getFileById("bgtrd");
var Newform1 = templateSheet.makeCopy(title+ " "+now,dumpfolder);
var qs = SpreadsheetApp.open(Newform1);
var dropSheet = qs.getSheetByName("DOC1");
var URL4 = Newform1.getUrl();
dropSheet.getRange("aa3").setValue(platform);
dropSheet.getRange("ah3").setValue(area);
dropSheet.getRange("ao3").setValue(works);
NewSEWO.setSharing(DriveApp.Access.DOMAIN, DriveApp.Permission.COMMENT);
NewSEWO.setOwner("Me");
sheet.appendRow([now,doctyp,name,title,platform,area,rota,works,URL4]);
GmailApp.sendEmail(recipient, title+ " has been created.", "Your document has been created." +'\n'+ "Here is the link to your copy! Link: " + URL4);
ui.alert("Email Sent", "An email has been sent with your documents link. You can also use the below link to view the document now, click ctrl C to copy. \
" + URL4, ui.ButtonSet.OK);
}
else{
ui.alert("Error, Please try again, make sure you are listing all required information.");
}
}
--HTML--
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form id="myform">
<div class="form-group">
<label for="Document_Type">Document Type</label>
<select class="form-control" id="Document_Type" name = "Document_Type" required="required">
<?
var SS = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Set Up");
var Avals = SS.getRange("A2:A").getValues();
var numberOfValues = Avals.filter(String).length;
var RangeVals = SS.getRange(2,1,numberOfValues).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeVals.length; ++i) { ?>
<option><?!= RangeVals[i] ?></option>
<? } ?>
</select>
</div>
<div class="form-group">
<label for ="Name">Your Name</label>
<select class="form-control" name='Name' id="Name" required="required">
<?
var AvalN = SS.getRange("E2:E").getValues();
var numberOfValuesN = AvalN.filter(String).length;
var RangeValsN = SS.getRange(2,5,numberOfValuesN).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsN.length; ++i) { ?>
<option><?!= RangeValsN[i] ?></option>
<? } ?>
</select>
</div>
<div class="form-group">
<label for="Platform">Platform</label>
<select class="form-control" id="Platform" name = "Platform" required="required">
<?
var AvalP = SS.getRange("C2:C").getValues();
var numberOfValuesP = AvalP.filter(String).length;
var RangeValsP = SS.getRange(2,3,numberOfValuesP).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsP.length; ++i) { ?>
<option><?!= RangeValsP[i] ?></option>
<? } ?>
</select>
</div>
<div class="form-group">
<label for="Area">Area</label>
<select class="form-control" id="Area" name = "Area" required="required">
<?
var AvalA = SS.getRange("D2:D").getValues();
var numberOfValuesA = AvalA.filter(String).length;
var RangeValsA = SS.getRange(2,4,numberOfValuesA).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsA.length; ++i) { ?>
<option><?!= RangeValsA[i] ?></option>
<? } ?>
</select>
</div>
<div class="block form-group">
<label for="Rotation">Rotation</label>
<select class="form-control" name='Rotation' id="Rotation">
<?
var AvalR = SS.getRange("F2:F").getValues();
var numberOfValuesR = AvalR.filter(String).length;
var RangeValsR = SS.getRange(2,6,numberOfValuesR).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsR.length; ++i) { ?>
<option><?!= RangeValsR[i] ?></option>
<? } ?>
</select>
</div>
<div class="block form-group">
<label for="WorkSt">Work Station</label>
<input type='text' name='WorkSt' id="WorkSt" />
</div>
<div class="block form-group">
<label for="Title">Title</label>
<input type='text' name='Title' id="Title" required="required"/>
</div>
<div class="block">
<button type="submit" class="action">Submit</button>
</div>
</form>
<script>
document.querySelector("#myform").addEventListener("submit",
function(e)
{
e.preventDefault(); //stop form from submitting
google.script.run.addNewItem(this);
google.script.host.close();//close this dialogbox
}
);
</script>
</body>
</html>
is there a way to have each if statement its own function?
For visibility purposes, you certainly can modify your code as
function addNewItem(form_data)//pulls data from form
{
var ui = SpreadsheetApp.getUi();
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var n = new Date();
var now = ((n.getMonth()+1) + "/" + n.getDate() + "/" + n.getFullYear());
var doctyp = form_data.Document_Type;
var name = form_data.Name;
var title = form_data.Title;
var platform = form_data.Platform;
var area = form_data.Area;
var rota = form_data.Rotation;
var works = form_data.WorkSt;
var recipient = Session.getEffectiveUser().getEmail();
if (form_data.Document_Type == "Text2"){
function1();
}
else if (form_data.Document_Type == "Text1"){
function2();
}
else{
ui.alert("Error, Please try again, make sure you are listing all required information.");
}
function function1(){
var dumpfolder = DriveApp.getFolderById("12345")
var templateSheet = DriveApp.getFileById("67890");
...
}
function function2(){
var dumpfolder = DriveApp.getFolderById("abcd")
...
}
Would this even help the speed?
Not really. To help up speed, you should rather try to implement Best Practices.
In particular: Reduce repeated calls to external services, including SpreadsheetApp.
For example, try to position the cells to which you want to assign values into an adjacent range, so you can use the method setValues() instead of multiple setValue() and thus make your code more efficient.
Sample:
var range = dropSheet.getRange("I8:N8");
var values = [];
values[0] = [];
values[0].push(title, now, platform, area, rota, works, name);
range.setValues(values);
Also, try to avoid repeating the same request for each if condition and rather make a single request after exiting the if statement, e.g. for:
sheet.appendRow([now,doctyp,name,title,platform,area,rota,works,URL3]);
GmailApp.sendEmail(recipient, title+ " has been created.", "Your document has been created." +'\n'+ "Here is the link to your copy! Link: " + URL3);
ui.alert("Email Sent", "An email has been sent with your documents link. You can also use the below link to view the document now, click ctrl C to copy. \
" + URL3, ui.ButtonSet.OK);
I hope this helps!

Django language selection from dropdown (links and images)

I could use this code:
mytemplate.html:
<form action="{% url 'set_language' %}" method="post">{% csrf_token %}
<input name="next" type="hidden" value="{{ redirect_to }}" />
<select name="language">
{% get_current_language as LANGUAGE_CODE %}
<option value='it' {% if 'it' == LANGUAGE_CODE %} selected{% endif %}> Italiano</option>
<option value='en' {% if 'en' == LANGUAGE_CODE %} selected{% endif %}> English</option>
</select>
<input type="submit" value="Go" />
</form>
It works translating my page without changing the url.
But I don't like how it look, I prefer a dropdown menù (it look better in my toolbar, also I can add images). I tried many things until I found this:
<a class='dropdown-toggle' data-toggle='dropdown' role='button'
aria-expanded='false'>Lingua<span class='caret'></span></a>
<ul class='dropdown-menu' role='menu'>
<li><a href="/it{{ request.get_full_path }}" class='language' lang='it'><img width='16' height='12' src="{% static 'icons/italian.png' %}" alt='Italiano' /> Italiano</a></li>
<li><a href="/en{{ request.get_full_path }}" class='language' lang='en'><img width='16' height='12' src="{% static 'icons/english.png' %}" alt='English' /> English</a></li>
</ul>
but this add a prefix to my url (it/ or en/) and my url haven't prefix, so it gives page not found 404.
Is there a way to use the standard django view with a dropdown menù?
Edit: here the django translation code, maybe it helps:
Envs>myproject>Lib>site-packages>django>conf>urls>i18n.py:
import warnings
from django.conf import settings
from django.conf.urls import patterns, url
from django.core.urlresolvers import LocaleRegexURLResolver
from django.utils import six
from django.utils.deprecation import RemovedInDjango110Warning
from django.views.i18n import set_language
def i18n_patterns(prefix, *args):
"""
Adds the language code prefix to every URL pattern within this
function. This may only be used in the root URLconf, not in an included
URLconf.
"""
if isinstance(prefix, six.string_types):
warnings.warn(
"Calling i18n_patterns() with the `prefix` argument and with tuples "
"instead of django.conf.urls.url() instances is deprecated and "
"will no longer work in Django 1.10. Use a list of "
"django.conf.urls.url() instances instead.",
RemovedInDjango110Warning, stacklevel=2
)
pattern_list = patterns(prefix, *args)
else:
pattern_list = [prefix] + list(args)
if not settings.USE_I18N:
return pattern_list
return [LocaleRegexURLResolver(pattern_list)]
urlpatterns = [
url(r'^setlang/$', set_language, name='set_language'),
]
Envs>myproject>Lib>site-packages>django>views>i18n.py:
import gettext as gettext_module
import importlib
import json
import os
from django import http
from django.apps import apps
from django.conf import settings
from django.core.urlresolvers import translate_url
from django.template import Context, Engine
from django.utils import six
from django.utils._os import upath
from django.utils.encoding import smart_text
from django.utils.formats import get_format, get_format_modules
from django.utils.http import is_safe_url
from django.utils.translation import (
LANGUAGE_SESSION_KEY, check_for_language, get_language, to_locale,
)
DEFAULT_PACKAGES = ['django.conf']
LANGUAGE_QUERY_PARAMETER = 'language'
def set_language(request):
"""
Redirect to a given url while setting the chosen language in the
session or cookie. The url and the language code need to be
specified in the request parameters.
Since this view changes how the user will see the rest of the site, it must
only be accessed as a POST request. If called as a GET request, it will
redirect to the page in the request (the 'next' parameter) without changing
any state.
"""
next = request.POST.get('next', request.GET.get('next'))
if not is_safe_url(url=next, host=request.get_host()):
next = request.META.get('HTTP_REFERER')
if not is_safe_url(url=next, host=request.get_host()):
next = '/'
response = http.HttpResponseRedirect(next)
if request.method == 'POST':
lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER)
if lang_code and check_for_language(lang_code):
next_trans = translate_url(next, lang_code)
if next_trans != next:
response = http.HttpResponseRedirect(next_trans)
if hasattr(request, 'session'):
request.session[LANGUAGE_SESSION_KEY] = lang_code
else:
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code,
max_age=settings.LANGUAGE_COOKIE_AGE,
path=settings.LANGUAGE_COOKIE_PATH,
domain=settings.LANGUAGE_COOKIE_DOMAIN)
return response
def get_formats():
"""
Returns all formats strings required for i18n to work
"""
FORMAT_SETTINGS = (
'DATE_FORMAT', 'DATETIME_FORMAT', 'TIME_FORMAT',
'YEAR_MONTH_FORMAT', 'MONTH_DAY_FORMAT', 'SHORT_DATE_FORMAT',
'SHORT_DATETIME_FORMAT', 'FIRST_DAY_OF_WEEK', 'DECIMAL_SEPARATOR',
'THOUSAND_SEPARATOR', 'NUMBER_GROUPING',
'DATE_INPUT_FORMATS', 'TIME_INPUT_FORMATS', 'DATETIME_INPUT_FORMATS'
)
result = {}
for module in [settings] + get_format_modules(reverse=True):
for attr in FORMAT_SETTINGS:
result[attr] = get_format(attr)
formats = {}
for k, v in result.items():
if isinstance(v, (six.string_types, int)):
formats[k] = smart_text(v)
elif isinstance(v, (tuple, list)):
formats[k] = [smart_text(value) for value in v]
return formats
js_catalog_template = r"""
{% autoescape off %}
(function(globals) {
var django = globals.django || (globals.django = {});
{% if plural %}
django.pluralidx = function(n) {
var v={{ plural }};
if (typeof(v) == 'boolean') {
return v ? 1 : 0;
} else {
return v;
}
};
{% else %}
django.pluralidx = function(count) { return (count == 1) ? 0 : 1; };
{% endif %}
/* gettext library */
django.catalog = django.catalog || {};
{% if catalog_str %}
var newcatalog = {{ catalog_str }};
for (var key in newcatalog) {
django.catalog[key] = newcatalog[key];
}
{% endif %}
if (!django.jsi18n_initialized) {
django.gettext = function(msgid) {
var value = django.catalog[msgid];
if (typeof(value) == 'undefined') {
return msgid;
} else {
return (typeof(value) == 'string') ? value : value[0];
}
};
django.ngettext = function(singular, plural, count) {
var value = django.catalog[singular];
if (typeof(value) == 'undefined') {
return (count == 1) ? singular : plural;
} else {
return value[django.pluralidx(count)];
}
};
django.gettext_noop = function(msgid) { return msgid; };
django.pgettext = function(context, msgid) {
var value = django.gettext(context + '\x04' + msgid);
if (value.indexOf('\x04') != -1) {
value = msgid;
}
return value;
};
django.npgettext = function(context, singular, plural, count) {
var value = django.ngettext(context + '\x04' + singular, context + '\x04' + plural, count);
if (value.indexOf('\x04') != -1) {
value = django.ngettext(singular, plural, count);
}
return value;
};
django.interpolate = function(fmt, obj, named) {
if (named) {
return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])});
} else {
return fmt.replace(/%s/g, function(match){return String(obj.shift())});
}
};
/* formatting library */
django.formats = {{ formats_str }};
django.get_format = function(format_type) {
var value = django.formats[format_type];
if (typeof(value) == 'undefined') {
return format_type;
} else {
return value;
}
};
/* add to global namespace */
globals.pluralidx = django.pluralidx;
globals.gettext = django.gettext;
globals.ngettext = django.ngettext;
globals.gettext_noop = django.gettext_noop;
globals.pgettext = django.pgettext;
globals.npgettext = django.npgettext;
globals.interpolate = django.interpolate;
globals.get_format = django.get_format;
django.jsi18n_initialized = true;
}
}(this));
{% endautoescape %}
"""
def render_javascript_catalog(catalog=None, plural=None):
template = Engine().from_string(js_catalog_template)
indent = lambda s: s.replace('\n', '\n ')
context = Context({
'catalog_str': indent(json.dumps(
catalog, sort_keys=True, indent=2)) if catalog else None,
'formats_str': indent(json.dumps(
get_formats(), sort_keys=True, indent=2)),
'plural': plural,
})
return http.HttpResponse(template.render(context), 'text/javascript')
def get_javascript_catalog(locale, domain, packages):
default_locale = to_locale(settings.LANGUAGE_CODE)
app_configs = apps.get_app_configs()
allowable_packages = set(app_config.name for app_config in app_configs)
allowable_packages.update(DEFAULT_PACKAGES)
packages = [p for p in packages if p in allowable_packages]
t = {}
paths = []
en_selected = locale.startswith('en')
en_catalog_missing = True
# paths of requested packages
for package in packages:
p = importlib.import_module(package)
path = os.path.join(os.path.dirname(upath(p.__file__)), 'locale')
paths.append(path)
# add the filesystem paths listed in the LOCALE_PATHS setting
paths.extend(reversed(settings.LOCALE_PATHS))
# first load all english languages files for defaults
for path in paths:
try:
catalog = gettext_module.translation(domain, path, ['en'])
t.update(catalog._catalog)
except IOError:
pass
else:
# 'en' is the selected language and at least one of the packages
# listed in `packages` has an 'en' catalog
if en_selected:
en_catalog_missing = False
# next load the settings.LANGUAGE_CODE translations if it isn't english
if default_locale != 'en':
for path in paths:
try:
catalog = gettext_module.translation(domain, path, [default_locale])
except IOError:
catalog = None
if catalog is not None:
t.update(catalog._catalog)
# last load the currently selected language, if it isn't identical to the default.
if locale != default_locale:
# If the currently selected language is English but it doesn't have a
# translation catalog (presumably due to being the language translated
# from) then a wrong language catalog might have been loaded in the
# previous step. It needs to be discarded.
if en_selected and en_catalog_missing:
t = {}
else:
locale_t = {}
for path in paths:
try:
catalog = gettext_module.translation(domain, path, [locale])
except IOError:
catalog = None
if catalog is not None:
locale_t.update(catalog._catalog)
if locale_t:
t = locale_t
plural = None
if '' in t:
for l in t[''].split('\n'):
if l.startswith('Plural-Forms:'):
plural = l.split(':', 1)[1].strip()
if plural is not None:
# this should actually be a compiled function of a typical plural-form:
# Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 :
# n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=', 1)[1]
pdict = {}
maxcnts = {}
catalog = {}
for k, v in t.items():
if k == '':
continue
if isinstance(k, six.string_types):
catalog[k] = v
elif isinstance(k, tuple):
msgid = k[0]
cnt = k[1]
maxcnts[msgid] = max(cnt, maxcnts.get(msgid, 0))
pdict.setdefault(msgid, {})[cnt] = v
else:
raise TypeError(k)
for k, v in pdict.items():
catalog[k] = [v.get(i, '') for i in range(maxcnts[msgid] + 1)]
return catalog, plural
...
I found a working solution, but please tell me if there is something wrong
mytemplate.html:
<a class='dropdown-toggle' data-toggle='dropdown' role='button'
aria-expanded='false'>{% trans "Lingua" %}<span class='caret'></span></a>
<ul class='dropdown-menu' role='menu'>
<li>
<form name="languageIt" action="{% url 'set_language' %}" method="post">{% csrf_token %}
<input name="next" type="hidden" value="{{ redirect_to }}" />
<input name="language" type="hidden" value="it" />
<img width='16' height='12' src="{% static 'icons/italian.png' %}" alt='it' /> Italiano
</form>
</li>
<li>
<form name="languageEn" action="{% url 'set_language' %}" method="post">{% csrf_token %}
<input name="next" type="hidden" value="{{ redirect_to }}" />
<input name="language" type="hidden" value="en" />
<img width='16' height='12' src="{% static 'icons/english.png' %}" alt='en' /> English
</form>
</li>
</ul>

How to update a specific value inside a dictionary using JQuery and Flask?

I've created a session list that contains my products, i need to update the quantity of any product by increasing it amount, for that am using an HTML type="number" , i also created a function which take the changed amount and multiplying it value with the current quantity, so lets say the amount of the first product by default is 2 by increasing the number lets say 2 the product amount will become 4 and so on, also the price will be multiplied .
Here are the codes:
<th style="text-align: center;" class="amount-izd">{{value["amount"]}}</th>
<th style="text-align: center; width: 14%;">
<div class="block">
<input type="number" id="myNumber" value="1" min=1 data-amount='{{value["amount"]}}' data-pros='{{value["id"]}}' data-price='
{% if g.currency == "euro" %}
{{format_price(value["price"] * config.SITE_CURRENCIES["euro"]).rsplit(".",1)[0]}}
{% elif g.currency == "dollar" %}
{{format_price(value["price"] * config.SITE_CURRENCIES["dollar"]).rsplit(".",1)[0]}}
{% else %}
{{format_price(value["price"] * config.SITE_CURRENCIES["ruble"]).rsplit(".",1)[0]}}
{% endif %}
'>
<label for="myNumber">qty</label>
</div>
</th>
JQuery codes:
$("input[type='number']").bind('keyup change click', function (e) {
if (! $(this).data("previousValue") ||
$(this).data("previousValue") != $(this).val()
)
{
var currentAmount = $(this).attr('data-amount');
var currentPrice = $(this).attr('data-price');
$(this).closest('tr').find('.amount-izd').text(parseInt(currentAmount) * $(this).val());
$(this).closest('tr').find('.price-izd').text(parseInt(currentPrice) * $(this).val());
$.ajax({
type: 'post',
url: '/standard-{{g.currency}}/profile/'+$(this).attr("data-pros")+'/update/price/' + parseInt(currentPrice) * $(this).val(),
cache: false
}).done(function(data){
if(data.error){
toastr.error(data.error)
}
});
$(this).data("previousValue", $(this).val());
} else {
}
});
And finally views.py :
#profile_route.route("/standard-<set_curr>/profile/cart/", methods=['GET','POST'])
#authorize
def cart_products():
if "cart" not in session:
return render_template("my-cart.html", display_cart = {}, total = 0)
else:
items = session["cart"]
dict_of_products = {}
total_price = 0
for item in items:
product = Goods.query.get(item)
total_price += product.price
if product.id in dict_of_products:
pass
else:
dict_of_products[product.id] = {"qty":1, "name":product.product_name, 'category':product.Category.name, "sizes": product.sizes, "hex_color":product.hex_color, "text_color":product.text_color, "material":product.material, "article":product.article, "price":product.price, "sort": product.sort, "amount": product.amount, 'slug':product.slug, 'public_id' : product.public_id, "id":product.id}
return render_template("my-cart.html", display_cart=dict_of_products, total = total_price)
#profile_route.route("/standard-<set_curr>/profile/<int:id>/update/price/<price>", methods=['GET','POST'])
#login_required
def update_price(id, price):
items = session["cart"]
dict_of_products = {}
for item in items:
product = Goods.query.get(item)
if product.id in dict_of_products:
dict_of_products[id]['price'] = price
return jsonify(success=dict_of_products[id]['price'])
return jsonify(error='No product found.')
If i changed the amount , in console i got a 500 error that says:
return jsonify(success=dict_of_products[id]['price'])
KeyError: 47
Please how to overcome this problem ?
Update:
I was wondering , is it possible to update any value of the dictionary by accessing it directly from JQuery ??

How to get values from select form to a python file with Flask

I've created a select options with html and templating in flask.
What I need to accomplish is to take the option values and put it inside my code, here is my html code :
<select id="oblast_select" name='areaid'>
<option value="0">0</option>
<option value="5971">value1</option>
<option value="7402">value2</option>
<option value="5219">value3</option>
<option value="4949">value4</option>
<option value="5764">value5</option>
<option value="7412">6</option>
<option value="6217">value7</option>
<option value="6802">value8</option>
<option value="6940">value9</option>
</select>
Also here is my java code that sends post request to python file:
var serviceid = document.getElementById("name_street").value;
var areaid = document.getElementById('oblast_select').value;
$(".btn").addClass("clicked");
$.post(
"/serviceidlookup",
{ serviceid: serviceid },
{ areaid: areaid }
).done(function (reply) {
$(".spinner").css("display", "block");
$('.spinner').fadeOut(5500);
setTimeout(function() {
$('#reply').empty().append(reply).fadeIn(3000);
}, 4000);`enter code here`
});
and finally my python file run.py:
#app.route('/serviceidlookup', methods=["GET", "POST"])
def serviceidlookup():
reload(sys)
sys.setdefaultencoding("utf-8")
sys.stdout.encoding
serviceid = request.form.get('serviceid')
areaid = request.args.get('areaid')
idarea = str(areaid)
con = psycopg2.connect(**config)
cur = con.cursor()
cur.execute("select ate,ate_type,name_kg,name_ru,name_en,parent from ate_history where ate in (select ate from street_ate where street in (select street from street_history where name_ru = '%s') and parent = %s)" %(serviceid,idarea))
entries = [dict(ate=row[0], ate_type=row[1], name_kg=row[2], name_ru=row[3], name_en=row[4], parent=row[5]) for row in cur.fetchall()]
return render_template('lookup.html', serviceid=serviceid, entries=entries)
After running this code, in the terminal gives me this error :
**LINE 1: ...om street_history where name_ru = 'None') and parent = None)**
infact, i get the serviceid value from the input field that i've created, it didn't get the other value which is in our case on of the options so for example 7402 to be inside the query at this part :
and parent = %s)"
Please any help would be toooooooons appreciated !!!!!!!
You have written
serviceid = request.form.get('serviceid')
areaid = request.args.get('areaid')
Try changing areaid to match the serviceid i.e
serviceid = request.form.get('serviceid')
areaid = request.form.get('areaid')
Edit: Try replacing
var areaid = document.getElementById('oblast_select').value;
with this..
var e = document.getElementById("oblast_select");
var areaid= e.options[e.selectedIndex].value;
Edit2: Change your jQuery post to this..
$.post(
"/serviceidlookup",
{ serviceid: serviceid },
{ areaid: areaid } , function (reply) {
$(".spinner").css("display", "block");
$('.spinner').fadeOut(5500);
setTimeout(function() {
$('#reply').empty().append(reply).fadeIn(3000);
}, 4000);
});
According to the Flask docs - http://werkzeug.pocoo.org/docs/0.10/datastructures/#werkzeug.datastructures.MultiDict the request.args.get() method will only return the first element by default. To get all the values you need to use a list method; request.args.getlist().