Translate selection fields from another model - Template Website Odoo 11 - templates

I have a selection type field who is coming another model. But, my traduction file do not take it into account. I am looking to find a other solution for translate values fields this select field.
Any idea ?
EDIT :
Here my template code :
...<table class="table table-hover table_requests" id="order_tableau">
<thead>
<tr>
<th scope="col">Reference</th>
<th scope="col">Type</th>
<th scope="col">Applicant</th>
<th scope="col">Date</th>
<th scope="col">State</th>
</tr>
</thead>
<tbody>
<t t-foreach="requests_grc" t-as="request_grc">
<tr id="result_requests" t-att-onclick="'window.location=\'/web#id='+str(request_grc.id)+'&view_type=form&model=website.application&menu_id=299&action=389\''"
t-att-class="'cursor-pointer'">
<td><t t-esc="request_grc.name"/></td>
<td><t t-esc="request_grc.website_application_template_id.name"/></td>
<td><t t-esc="request_grc.applicant_id.name"/></td>
<td><t t-esc="request_grc.date" t-options="{'widget': 'date'}"/></td>
<td><t t-esc="request_grc.state"/></td>
</tr>
</t>
</tbody>
</table>...
Here my Python code :
requests_grc = http.request.env['website.application'].search([])
Result
I would translate the last element on my table : request_grc.state
EDIT :
#http.route('/web_demarches/', auth='user', website=True)
def indexDemarches(self, **kw):
user = http.request.env.user.name
active_new = False
active_in_progress = False
active_completed_request = False
active_refused_request = False
nb_new_request = 0
nb_in_progress_request = 0
nb_completed_request = 0
nb_refused_request = 0
requests_grc = http.request.env['website.application'].search([])
requests_grc_new = http.request.env['website.application'].search([('state', '=', 'new')])
requests_grc_in_progress = http.request.env['website.application'].search(['|', ('state', '=', 'in_progress'),
('state', '=', 'is_pending')])
requests_grc_completed = http.request.env['website.application'].search([('state', '=', 'completed')])
requests_grc_refused = http.request.env['website.application'].search([('state', '=', 'rejected')])
for request_new in requests_grc_new:
nb_new_request = nb_new_request + 1
for request_in_progress in requests_grc_in_progress:
nb_in_progress_request = nb_in_progress_request + 1
for request_completed in requests_grc_completed:
nb_completed_request = nb_completed_request + 1
for request_refused in requests_grc_refused:
nb_refused_request = nb_refused_request + 1
return http.request.render('grc_parthenay.demarches', {
'user': user,
'active_new': active_new,
'active_in_progress': active_in_progress,
'active_completed_request': active_completed_request,
'active_refused_request': active_refused_request,
'requests_grc': requests_grc,
'requests_grc_new': requests_grc_new,
'requests_grc_in_progress': requests_grc_in_progress,
'requests_grc_completed': requests_grc_completed,
'requests_grc_refused': requests_grc_refused,
'nb_new_request': nb_new_request,
'nb_in_progress_request': nb_in_progress_request,
'nb_completed_request': nb_completed_request,
'nb_refused_request': nb_refused_request,
})

Related

Could not parse some characters: video.viewers.all.count| ans video.viewers_by_ip.all.count||intcomma

How I can parse or sum two ManyToMany field in the template
<div class=""> <h6 class="card-text ml-2 p-2 bd-highlight" style="text-align: left; height: 1px; "><small class="text-muted ">{{ video.viewers.all.count + video.viewers_by_ip.all.count|intcomma }} views . </small></h6></div>
I tried to get this number by my view but I got this message
'list' object has no attribute 'viewers_by_ip'
my view
profile = get_object_or_404(Account, username=request.user)
if not profile.is_active:
return render(request, 'personal/violated.html')
users = [user for user in profile.following.all()]
video = []
for u in users:
p = Account.objects.get(username=u)
p_posts = p.video_set.all()
video.append(p_posts)
my_post = profile.account_video()
video.append(my_post)
if len(video):
video = sorted(chain(*video), reverse=True, key=lambda video: video.created_date)
video_viewers_ip = video.viewers_by_ip.all()
video_viewers = video.viewers.all()
video_views = len(list(chain(video_viewers_ip, video_viewers)))

converting Wildcard to Regex

I'm new in MVC, I want to perform Wildcard (*, ?) search on database. This is what I have done by using Regex:
Controller:
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
CrossWord_dbEntities db = new CrossWord_dbEntities();
public ActionResult Index(string searching)
{
if (searching == null)
{
searching = "*";
}
string regEx = WildcardToRegex(searching);
return View(db.tbl_values.ToList().Where(x => Regex.IsMatch(x.Name, regEx, RegexOptions.Singleline)));
}
public static string WildcardToRegex(string pattern)
{
return "^" + Regex.Escape(pattern).
Replace("\\*", ".*").
Replace("\\?", ".") + "$";
}
}
}
View:
#model IEnumerable<WebApplication1.Models.tbl_values>
<br /><br />
#using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
#Html.TextBox("searching") <input type="submit" value="Search" />
}
<table class="table table-striped">
<thead>
<tr>
<th>Results</th>
</tr>
</thead>
<tbody>
#if (Model.Count() == 0)
{
<tr>
<td colspan="3" style="color:red">
No Result
</td>
</tr>
}
else
{
foreach (var item in Model)
{
<tr>
<td>
#item.Name
</td>
</tr>
}
}
</tbody>
</table>
i have in my database three recordes: Hello, Hero, Shalom
when i type " H* " i get the result: Hello, Hero - this works great
but when i type " *lom " i get "No Result" instead of "Shalom"
or when i type " Hell?" i get "No Result" instead of "Hello"
what i did wrong ?
You can use the following
Expression<Func<tbl_value, bool>> query = m =>
SqlFunctions.PatIndex(searching.ToLower().Replace("*", "%"), m.Name.ToLower()) > 0;
var details = db.tbl_values.Where(query);
Hope this will help you

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 ??

django-datatables-view not displaying content returned from AJAX request?

My Ajax request to update the tables is not working. Attached is the screenshot. It simply displays "processing" but nothing happens. The JSON object that is returned (if i visit the URL -{% url 'search_list_json' %} --used in AjaxSource of Js code below) seems to be correct. but still the mainpage is not displaying the JSON content in table.
Here it is:
{"result": "ok",
"iTotalRecords": 1, "aaData": [["<center><font color=\"red\">Mazda=>626:2012-1986</font>\n </center>", "04/07/2014", "10000", "1000", "<center><a href='/search/update/1/'><img src='/static/images/icons/icon_changelink.gif'></a> <a href='/search/delete/1/'><img src='/static/images/icons/icon_deletelink.gif'></a></center>"]],
"sEcho": 0,
"iTotalDisplayRecords": 1}
My views.py
class SearchListJson(BaseDatatableView):
model = Search
columns=['title','created','max_price', 'min_price','actions']
order_columns = ['created', 'max_price']
max_display_length = 500
def render_column(self, row, column):
user = self.request.user
url_edit=static('images/icons/icon_changelink.gif')
url_delete=static('images/icons/icon_deletelink.gif')
#print url_edit, url_delete
if column == 'title':
value = '{0}=>{1}:{2}-{3}'.format(row.vehicle_make,row.vehicle_model,
row.max_year,row.min_year)
edit_url = reverse('search_detail', args=(row.id,))
#print self.get_value_cell_style(edit_url, value,'red')
return self.get_value_cell_style(edit_url, value,'red')
elif column == 'max_price':
#print '%s' %row.max_price
return '%s' %row.max_price
elif column == 'min_price':
#print '%s' %row.min_price
return '%s' %row.min_price
elif column == 'created':
#print row.created.strftime('%m/%d/%Y')
return row.created.strftime('%m/%d/%Y')
elif column == 'actions':
print "in columns actions"
edit_link = """<a href='%s'><img src='%s'></a>""" %(\
reverse('search_update', args=(row.id,)),url_edit)
delete_link = """<a href='%s'><img src='%s'></a>""" %(\
reverse('search_delete', args=(row.id,)),url_delete)
print "edit_link", edit_link
print "delete_link",delete_link
return '<center>%s %s</center>' % (edit_link, delete_link)
else:
return super(SearchListJson, self).render_column(row, column)
def get_value_cell_style(self, url, value, color=None):
style = '''<center>%s</center>''' % (url, value)
if color:
style = '''<center><font color="%s">%s</font>
</center>''' % (url, color, value)
return style
def get_initial_queryset(self):
"""
Filter records to show only entries from the currently logged-in user.
"""
#print "get intial queryset called"
#print Search.objects.filter(user=self.request.user)
return Search.objects.filter(user=self.request.user)
The js-code is below:
$(document).ready(function() {
var oTable = $('#search_table').dataTable( {
"sDom": 'T<"clear">lrtip',
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "{% url 'search_list_json' %}",
"aaSorting": [ [1,'desc'], [2,'desc'] ],
// Disable sorting for the Actions column.
"aoColumnDefs": [ { "bSortable": false, "aTargets": [ 4 ] } ]
} );
} );
The HTML is:
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-12">
<div class="well">
<table id="search_table">
<thead>
<tr>
<th width="10%"><center>Title</center></th>
<th width="15%">Date Created</th>
<th width="15%">Min Price</th>
<th width="15%">Max Price</th>
<th width="10%"></th>
</tr>
</thead>
</table><br>
</div>
</div>
</div>

Freemarker List inside a a table

I'm trying to generate a table with freemarker.
<table class="timeline">
<tr>
<#list children as child >
<td class="timeline-item">${child.title}</td>
<td><img class="sitelink_arrow" src="images/arrow.png"/></td>
</#list>
</tr>
</table>
This will generate an error :
Was expecting one of: ... ... ... ... ... ... ... ... <_INCLUDE> ...
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... "${" ...
"#{" ...
If I put this list outside the table then it works just fine.
Any ideas ?
Your code should be look like this:
It is better if you post your code as well.
And full error also.
[#ftl]
<table id="timelineTable" class="timeline" align="left" width="100%">
[#if children?? && children?size > 0]
[#list children as child]
<tr>
<td class="timeline-item">
${child.title}
</td>
<td>
<img class="sitelink_arrow" src="images/arrow.png"/>
</td>
</tr>
[/#list]
[#else]
No Details Available
[/#if]