removing more than a character using cut - django

So I'm trying to search for Elements using query selector, the problem is, due to the way theses IDs are generated (with the name of regions, stores, and sale type, from the context) some of then includes spaces or dots on them which don't let them be searched.
I have identified the spaces were breaking my searches before and used cut to remove the spaces from IDs.
Is there a way to use cut to remove diferent characters as if I'm using cascaded replaces (in python) or replaceAlls (in JS) to make these ids don't have any spaces or dots? I tried using pipes but it didn't work. how can I do it?
Snippet of the formation of the elements:
{% if data.nivel == "N0" %}
<tr id="family_{{ data.familia_produto|cut:" " }}" class="bu_name_line {{ data.nivel }} title0"
data-level="{{ data.nivel }}" data-family="{{ data.familia_produto }}"
data-regional="{{ data.nome_regional }}" data-segment="{{ data.segmento }}"
data-bu-name="{{ data.nome_filial }}" onclick="show_lines('N1','{{ data.familia_produto }}')">
<td id='bu_name' onmouseenter='hight_light(this)' onmouseleave='hight_light(this)'>
{{ data.familia_produto }}
</td>
{% elif data.nivel == "N1" %}
<tr id="regional_{{ data.familia_produto|cut:" " }}_{{ data.nome_regional|cut:" " }}"
class="bu_name_line {{ data.nivel }} title1 hide" data-level="{{ data.nivel }}"
data-family="{{ data.familia_produto }}" data-regional="{{ data.nome_regional }}"
data-segment="{{ data.segmento }}" data-bu-name="{{ data.nome_filial }}"
onclick="show_lines('N2A','{{ data.familia_produto }}','{{ data.nome_regional }}')">
<td id='bu_name' onmouseenter='hight_light(this)' onmouseleave='hight_light(this)'>
{{ data.nome_regional }}
</td>
Snippet of the selection I'm trying to do to catch this elements:
if (level_name[0] == 'family'){
var forecast_lines = line.parentElement.querySelectorAll(`[id*=regional_${level_name[1]}]`)
}else if (level_name[0] == 'regional'){
var forecast_lines = line.parentElement.querySelectorAll(`[id*=filial_${level_name[1]}_${level_name[2]}]`)
}else if (level_name[0] == 'filial'){
//console.log("entrei aqui 222222222")
var forecast_lines = line.parentElement.querySelectorAll(`[id*=segmento_${level_name[1]}_${level_name[2]}_${level_name[3]}]`)
error:
Uncaught DOMException: Element.querySelectorAll: '[id*=segmento_CAFES_INTERNA_GER.INT.COMERCIAL]' is not a valid selector

Don't know exactly how is your code but it will give you an idea:
should_removed_list = [" ", ".", ",", "="]
for i in should_removed_list:
if str(i) in your_content:
your_content.replace(str(i), "")

Related

How can select and load form?

I want to select option 1 and load a form with inputs
HTML:
<select id="orden" class="form-control" name="orden">
<option disabled selected>Selecciona una opciĆ³n</option>
<option value="1">{{ results.1.op_ser_codigo }}{{ results.1.op_num_codigo }} / ({{ results.1.data_ini }} - {{ results.1.data_fim }})</option>
<option value="2">{{ results.2.op_ser_codigo }}{{ results.2.op_num_codigo }} / ({{ results.2.data_ini }} - {{ results.2.data_fim }})</option>
<option value="3">{{ results.3.op_ser_codigo }}{{ results.3.op_num_codigo }} / ({{ results.3.data_ini }} - {{ results.3.data_fim }})</option>
<option value="4">{{ results.4.op_ser_codigo }}{{ results.4.op_num_codigo }} / ({{ results.4.data_ini }} - {{ results.4.data_fim }})</option>
<option value="5">{{ results.5.op_ser_codigo }}{{ results.5.op_num_codigo }} / ({{ results.5.data_ini }} - {{ results.5.data_fim }})</option>
<option value="6">{{ results.6.op_ser_codigo }}{{ results.6.op_num_codigo }} / ({{ results.6.data_ini }} - {{ results.6.data_fim }})</option>
</select>
I want to fill this: (If on select option i select 1 on this inputs fill value 1)
<b><p class="black">OP: </b>{{ results.1.op_ser_codigo }}{{results.1.op_num_codigo}} </p>
<b><p class="black">Fecha Inicio: </b>{{ results.1.data_ini }} </p>
<b><p class="black">Fecha Final: </b> {{ results.1.data_fim }} </p>
You can handle it on client side (with jq, javascript) or on the server side. I definitely advice to handle it on the server side - as business logic should be there. Although in this case - as I understand - the trigger will come after the form is loaded and once the select options is selected.
I would go with an ajax solution.
place an onchange event to the select:
eg:
onchange="ChooseOption(this.value)"
add javascript to handle ajax request(I use jquery):
function ChooseOption(option_id){
$.ajax({
type: "POST",
url: "/applicatioin/option_selection/",
data: {
'option_id' : option_id,
'csrfmiddlewaretoken' :
$("input[name=csrfmiddlewaretoken]").val()
},
success: chooseoptionDetailSuccess,
dataType: 'html'
});
}
In the success you call chooseoptionDetailSuccess function. Which should pass the data to the relevant html field - with innerHtml.
Note: you may also use GET request type.
In you django view you have to render a html template which holds the html part (with the variables) which will be changed.
Sorry for the format. Seems like the code sample is not working.

queryset update with multiple variables duplicate

I am having an issue that I have database updated with the same value as for both id's even though they are different as per my example below:
Lets assume that I entered as input for id 1 -- P_350 =" try_1" id 2 -- P_350 = "try_2" when I click submit then it become both id's the same "try_2" value.
What you suggest to overcome this situation.
Should I need to use variable input name including the id in front of the input name ?
Or any easier method ?
I have the below view.py for my database updates:
ids = request.POST.getlist("id")
qs = fp.objects.filter(id__in=ids)
P_350 = request.POST["P_350"]
P_450 = request.POST["P_450"]
updates = {}
if len(P_350) > 1:
updates['P_350'] = P_350
if len(P_450) > 1:
updates['P_450'] = P_450
if updates:
qs.update(**updates)
Here is my html file input section:
<td style="display:none;">
<input name="id" type="text" value={{ field.id }} >
</td>
<td width="650">
{{ field.FP_Item }}
</td>
{% if field.P_350|length == 0 %}
<td style="display:none;">
{% else %}
<td>
{% endif %}
<input name="P_350" type="text" value={{ field.P_350 }} >
</td>
{% if field.P_450|length == 0 %}
<td style="display:none;">
{% else %}
<td>
{% endif %}
<input name="P_450" type="text" value={{ field.P_450 }} >
</td>
Wrong logic
If you putting different value at same input P_350 this will get the last value you place when it reaches the backend, you probabily should put your first value in P_350 and the second in P_450.
In your example you only manipulate P_350 2 times... so P_450 will never be updated because he dont have a new value.
If you have multiple inputs related with P_350, you should first get all first and then send to backend (AJAX like async) or place multiple P_350 with different names and handle it at backend when save each one
https://medium.com/#taranjeet/adding-forms-dynamically-to-a-django-formset-375f1090c2b0

Controlling whitespace in Pebble templates

I'm having a hard time getting the whitespace control the way that I want in a Pebble template. I'm currently generating JSON using Pebble, but this problem and my use case is not specific to JSON (or else I would use a JSON library, such as Jackson instead).
Here's my Pebble template:
"items": {
{% for item in items -%}
"{{ item.name }}": "{{ item.value }}"{% if not loop.last %},{% endif %}
{% endfor %}
},
And, here's the generated output:
"items": {
"item1": "Value 1",
"item2": "Value 2"
},
There are two problems with this:
I had to have the two blank lines in the template (one before the endfor and one after the endfor.
I still end up with the extra blank line in the output before the closing squiggly bracket, i.e. the },.
I'd like for the template to look more like the following:
"items": {
{% for item in items -%}
"{{ item.name }}": "{{ item.value }}"{% if not loop.last %},{% endif %}
{% endfor %}
},
And, I'd like for the resulting output to be:
"items": {
"item1": "Value 1",
"item2": "Value 2"
},
I have tried many combinations of the whilespace control modifier, but no luck on getting the format that I want.
Whitespace control modifier only trim lines. It doesn't remove line feed. The only solution for your use case is to remove blank lines around {% endfor %}

Edit multiple records in one template

I'm not at all sure that my approach to this problem is valid, so I'll appreciate "strategic" recommendations. From the other hand I hope to get some educational value from resolving the problem as it is.
I have a model Record and I want to edit values of several instances of it at once, on the same page.
That is ~how my edit form should looks like
For that I created this template:
**template.html**
#with some omissions
{% for record in records %}
<td>
<input type ="text"
name="position_for_record_{{ record.id}}"
value ="{{ record.position }}"
size ="3">
</td>
<td>
<input type ="text"
name="hours_for_record_{{ record.id }}"
value = "{{ record.hours }}"
size ="3">
</td>
<td>
<input type ="text"
name="tips_for_record_{{ record.id}}"
value = "{{ record.tips }}"
size ="3">
</td>
{%endfor%}
After submitting this form I'll get all those fields in the request.POST, the question is how to extract them? I can, of course, iterate through ALL records
**views.py**
def form_returns_here(request):
all_records=Record.objects.all()
for record in all_records:
if "position_for_record_"+str(record.id) in
request.POST:
But it just doesn't seem right.
Thank you.

Golang pagination

I need to implement pagination. Actually I have pages array, page param and per_page variable.
In my code:
pages_count := math.Floor(float64(len(pages)) / float64(per_page))
then in template I need something like (pseudocode):
{{ if .page - 2 > 0 }}
{{ $start_page := .page - 2 }}
{{ else }}
{{ $start_page := 1 }}
{{ end }}
{{ if .page + 2 >= .pages_count }}
{{ $finish_page := .page + 2 }}
{{ else }}
{{ $finish_page := .pages_count }}
{{ end }}
<ul>
{{ for $i := $start_page; $i <= $finish_page; ++$i }}
<li {{ if $i == .page }} class="current_page" {{ end }}>
$i
</li>
{{ end }}
</ul>
How to implement this correctly?
Thx
When I work with Java templates (e.g. Velocity), I find that the kinds of template logic you are asking about lead to over-complex templates. The same applied in Go.
My solution is to move logic into the view-model layer and keep the templates rather dumb. This means that the controller and view model have to do a bit more work precomputing the kinds of values that your template shows. The view model is consequently larger - but it's just simple data and is easy to unit-test.
In your specific example, you would keep the for-loop that builds up the <li> list. Everything above the <ul> open tag can be handled in the view model. So the template would just work with some precomputed data.