Ordered list form value in Django form - django

Is there a way to submit an unbounded list of values as part of a form and retrieve it in Django as an ordered list? I saw this question: Django equivalent of PHP's form value array/associative array which makes sense, however since the values are submitted with the same name as separate POST values I assume they are unordered.
Ideally, I'd like this on the front end:
<input type="hidden" name="list[0]" value="blah">
<input type="hidden" name="list[1]" value="blah2">
<input type="hidden" name="list[2]" value="blah3">
and be able to see which list item occurred in which position when the form was submitted.
I want it sorted in an order determined in the front-end HTML, not sorted by value. I know about getlist(), but that doesn't preserve order.

As far as I'm aware, the square bracket notation is a convention of PHP rather than HTML per se.
There seems to be a Django workaround using dot notation to generate expanded dictionaries (http://stackoverflow.com/questions/2527476/phps-form-bracket-trick-is-to-djangos). I haven't tried it, but it seems it could work
The other solution is to parse the form names yourself, extracting the number from the square brackets and generating your own ordered list
(DISCLAIMER: I'm a mere casual programmer, and am more than willing to acknowledge that im wrong - but hopefully the SO moderation system will moderate any silly comments into oblivion)

Related

Is it better to have an explicit django model field or calculate on demand?

If I have a django model that has an field called 'order' (integer field that tracks the modifiable order of a specific model instance amongst all model instances), and I also want to track the position of the model instance based on that order ('first'/'mid'/'last'), is it better to have another model field called 'position', which I recalculate and store each time there is a change to order, or should I have a model method called 'get_position' which I call each time I need a position. I'm trying to work out which is more efficient. Whilst I won't need the position information each time I create/delete/modify a instance order, I will need that position field quite a bit within my templates.
Generally avoid creating an additional database fields if something can be calculated from data already in the db, to prevent redundancy and reduce vectors for errors.
A method may work if its relatively simple, deriving its value from an existing field within the record. If it needs to look up comparative values from other records that would be an efficiency issue.
As you mention use in templates specifically, it may be worth seeing if the template builtins can meet your requirements.
Say your recordset is already in order of the 'order' field eg,
MyRecords.objects.order_by('order')
When looping through MyRecords_context in a template using a for loop, you can test for {{if forloop.first}} or {{if forloop.last }} - you can also refer to MyRecords_context.first() and .last() to single those out. If you need the specific index of a given record in that particular recordset for you template, you can refer to {{ forloop.counter }} eg {{if forloop.counter < 10 and forloop.counter > 5}} or {{if forloop.counter == 5}}
The advantage of this approach is that if you have a filtered a subset of your records, you are still referring to the first, last or Nth records of the recordset, even though they may not be first and last overall in your absolute position field, and with no additional db calls.

Coldfusion ignores posted html array fields

I am posting an html form which multiple input names look like that: left_impedance_TYMP[]
However when accessing them in coldfusion, it ignores empty fields.
FORM["left_impedance_TYMP[]"]
Inspecting POST request seems correct.
Is there a solution on this?
When you have multiple form fields of the same name, with or without brackets, both a GET and a POST ignore empty fields values.
Form:
<form action="brackets_process.cfm" method="GET">
<input type="text" name="foo" value="A"><br>
<input type="text" name="foo" value="B"><br>
<input type="text" name="foo" value="C"><br>
<input type="text" name="foo" value="D"><br>
<button>Submit</button>
</form>
Processing:
<cfdump var="#url#" label="URL">
<p></p>
<cfdump var="#form#" label="FORM">
A GET querystring brackets_process.cfm?foo=A&foo=B&foo=C&foo=D
A POST brackets_process.cfm
If you add brackets to foo[], the querystring is encoded and the struct key contains the brackets.
brackets_process.cfm?foo%5B%5D=A&foo%5B%5D=B&foo%5B%5D=C&foo%5B%5D=D
A POST is still a list of submitted values.
Converting POST data to an array.
PHP automatically converts field names that end with a bracket to an array. ColdFusion has an application.cfc setting this.sameformfieldsasarray=true; that #Alex linked. Problem is that its a global setting and could change a considerable amount of existing functionality.
With that setting on, a POST converts the values to an array.
A GET sticks to a list. So if you leave out a value (B), the value of url["foo[]'] is a list with 4 elements, where the 2nd element is empty.
Leaving a value (B) out of a POST, however, returns an array with 4 elements, where the 2nd value is empty.
So you need to determine if you want to make a global change that affects all current functionality or if you can add some conditional logic that checks the number of elements in a list vs. the expected number of fields.
I've written code in the past that named fields something like name="fieldName.#counterValue#", then parsed the field names to set positional values in a list or array to account for empty values.

Regex expression with Validators.pattern for just integer number

I am trying to create a validator for only integers (e.g., 60) using Regex.
Here how I am trying to do it:
meter: ["", Validators.required, Validators.pattern(/[0-9]/)]
It does not work, but I have to say I am not familiar with this technique.
Anyone could shed some light on how I could modify this expression to accept just integers?
This number is for height, and the height is devided into meters and centimeter.
I have searched, but I could find for decimals and so, somehow, maybe because it is too trivial, for just integers, I cannot find, in fact, I have found yesterday here, but I cannot find the answer anymore I have found, I was looking for another thing.
First of all, you don't need a custom validator to do this, as regular expression validation is already a built-in validator.
Secondly, the way you apply validators to your form controls depending on either you are using template-driven forms or reactive forms.
If you are using template-driven forms (which is commonly used for Angular beginners), simply make your input control template look like this:
<input type="number" name="meter" required pattern="[0-9]" [(ngModel)]="meter">
If you are using reactive forms, just assign both "required" and "pattern" validator to your form control.
<input type="number" [formControl]="myControl">
myControl = new FormControl(null, [
Validators.required,
Validators.pattern("[0-9]+")
]);
When using it in a reactive form control, you can pass in either a string or a regex object, there are differences between them as stated in official docs:
If a string is passed, the ^ character is prepended and the $ character is appended to the provided string (if not already present), and the resulting regular expression is used to test the values.
Lastly, a Stackblitz example attached to show simple usage of this validator in both template/reactive forms.
https://stackblitz.com/edit/angular-ivy-neux3n

django form with multiple choice field with potentially infinite choices

I have a model with a many-to-many field that will expand as the user adds more entries for the model. In the form template if I use the conventional {{ form.field }} I get a multiple choice select as is expected, but the problem that will quickly become apparent is when there are 10, 100, 1000 or more choices. What I'd like to provide in the form is a search field where the user can search through all available entries and via AJAX return entries matching their search criteria where they can then select the individual entry choices to be saved in the database.
I'm assuming I will have to manually render the multiple choice form field, but after hours of research I cannot find an example of this anywhere online. Is there an example that exists and I just haven't been able to find? How is one supposed to manually create a form with a multiple choice field in Django? Or am I going about this all wrong?

django template: iterate and print just items with index for example 3,6,9

Is there is some good way to iterate through list in django template and print just items with index which is for example 3,6,9 and so on...
Let's imagine I have list like this:
({'title':'first'}, {'title':'second'}, {'title':'third'}, .... {'title':'ninth '})
And in template I want to see just:
third
sixth
ninth
I know how to pass variable to template, I construct in a view, but just need the way how to iterate through them in template and print just what I want.
Or I need to construct list (or dictionary maybe) somehow differently? Using latest Django.
Thanks,
Ignas
The slice filter will allow you to slice a sequence just as you would in Python.
{{ mylist|slice:"2::3" }}