get values from multiple inputs with same key django - django

I'm fighting against the django forms. When I've solved one problem a new one appears, well I got a "dynamic" html with 3 types of forms.
class NameForm(forms.Form):
text = forms.CharField(widget=forms.TextInput(attrs={'id': 'field1'}))
select = forms.ChoiceField(widget = forms.Select(attrs={'id': 'field1'}), choices = ([('default','Select option')]), initial='default')
date = forms.DateField(widget=DateTypeInput(attrs={'id': 'field1'}))
And via JavaScript I create one type or other:
var createElement={
'text': '{{ form.text }}',
'select':'{{ form.select }}',
'date': '{{ form.date }}',
}
Then I want to get all type of elements created but the problem is there are multiple inputs with name "text" or select or date.
I parse this data with method GET and this one uses a dictionary. This dict only can have one key "text".
How can I solve this problem? Thanks a lot.

You can use request.GET.getlist('text') to get multiple values as a list.
But you are probably better off using formsets for something like this.

Related

Is there any way to determine attribute is select/choice in django model?

Currently implementing searchbox which provides two interface - textbox if required input is not normalized, and dropdown if required input is normalized and is defined with choices param in model, and select class in form.
Current model(partial):
id = models.CharField(args)
submitter = models.CharField(args)
experiment_type = models.CharField(args, choices=<tuple with choices>)
Current form.Meta.widgets for model above:
'id': TextInput(attrs={'id':'exp_id', readonly: ''})
'experiment_type': Select(attrs={'id': 'experiment_type', required=''})
I've currently found that I can retrieve each fields' html snippet by doing str(field), for field in form, and with beautifulsoup or other html parsing library I can find input type(is text field or dropdown(select)), and option values for dropdown.
But it seems too compilcated, and I'm currently guessing that there might be
some way django provides to determine such things.Looking forward, and thanks in advance for any help.

django tables2 create extra column with links

I am trying to add a extra column to one of my tables, that adds url to another page.
My Table:
class ItemTable(tables.Table):
edit = tables.LinkColumn('item_edit', args=[A('pk')])
class Meta:
model = Item
fields = ('name', 'slot', 'klass', 'rarity', 'price')
my urls:
url(r'^admin/item/edit/(?P<item_id>\d+)/$', views.item_edit, name='item_edit')
Now with this, i get my table, but the last column (edit) only has dashes + the page crashes when i click the title.
i have been looking at http://django-tables2.readthedocs.org/en/latest/#django_tables2.columns.LinkColumn and im not sure where i go wrong
The problems you've encountered are caused by LinkColumn expecting to be bound to a specific attribute in your Item model, i.e. it is looking for an Item.edit attribute on your instances.
Since you don't actually have an Item.edit attribute, ordering over your edit column makes no sense, and you should mark it as non-orderable:
from django_tables2.utils import A
edit = tables.LinkColumn('item_edit', args=[A('pk')], orderable=False)
The text of the link itself would come from the value of the Item.edit attribute, which you don't have, so you will need to provide it yourself by adding a render_edit method to your table class:
def render_edit(self):
return 'Edit'
You can replace the 'Edit' string with whatever you want displayed in that column.
Update: As suggested by #SunnySydeUp, you also need to specify empty_values=() for the column, in order to get its value rendered:
edit = tables.LinkColumn('item_edit', args=[A('pk')], orderable=False, empty_values=())
References:
http://django-tables2.readthedocs.org/en/latest/pages/order-by-accessors.html#specifying-alternative-ordering-for-a-column
http://django-tables2.readthedocs.org/en/latest/pages/custom-rendering.html#table-render-foo-methods
Disclaimer: This answer is based on the django-tables2 documentation and source code, and hasn't been tested on an actual Django application.
To have the link properly formatted and with a link text of your choice, you can do the following in the table class:
def render_edit_link(self,record):
return mark_safe('<a href='+reverse("edit", args=[record.pk])+'>Edit</a>')
Where 'edit' is the name of the url.
I create clickable links in extra columns with
edit = tables.LinkColumn('item_edit', text='Edit', args=[A('pk')], \
orderable=False, empty_values=())
It's not necessary to override the render method; the 'text' parameter changes the text of the link from 'none' to 'Edit', for example.

Using "record" in attributes Django Tables 2

I'm moving my tables to django-tables2. By now is almost everything working ok, but now I have a problem.
In my current version i use checkboxes to select items
<td><input type="checkbox" class="checkbox_delete" name="event" id="event.id"
value="{{ event.id }}" />
this way in the view i can recover the event.id using request.POST.getlist('event')
Now I'm trying to add the "value" attribute to a CheckBoxColumn
select = tables.CheckBoxColumn(attrs={'td__input': {'class': 'checkbox_delete', 'name': 'event', **'value': [A('id')]**}, 'th__input': {'id': 'selectAll'}},
empty_values=())
I've been playing with the Accesor and the record.id which I use in a templateColumn.
How can I pass the id to the value attribute??
You can simply do something like this:
id = tables.CheckBoxColumn()
This way, the column will be rendered like this
<input type="checkbox" name="id" value="X">
where X will be the value of the id field.
Now for a more complete answer:
You can add td__input to override some defaults but I don't believe what you can set it to different values for each column ! By checking the source:
https://github.com/bradleyayers/django-tables2/blob/master/django_tables2/columns/checkboxcolumn.py
you will see that in the render method in CheckBoxColumn will create an AttributeDict containing the attributes from input, td__input and some defaults, like this:
def render(self, value, bound_column): # pylint: disable=W0221
default = {
'type': 'checkbox',
'name': bound_column.name,
'value': value
}
general = self.attrs.get('input')
specific = self.attrs.get('td__input')
attrs = AttributeDict(default, **(specific or general or {}))
return mark_safe('' % attrs.as_html())
So the attrs you define will be the same in all columns since attrs.as_html will just convert the 'x':'y' dict entries to x=y...
So if you want to have total control and do whatever you like with the values for each column, just subclss CheckBoxColumn and override render (left as an excersise to the reader).
Update
Also, a very nice thing about your own render method is that you don't need to define the same parameters as the base one. This is because django-tables2 uses the getargspec function to find out which arguments your render expects and pass them to the render method. So, if you take a look at the https://github.com/bradleyayers/django-tables2/blob/master/django_tables2/rows.py you will see that the available parameters that can be passed to render, along with their values are:
available = {
'value': value,
'record': self.record,
'column': bound_column.column,
'bound_column': bound_column,
'bound_row': self,
'table': self._table,
}
So, for instance you can define your render method like:
def render(self, value, bound_column, record):
to also pass the record to it.
I found another solution here How to get information from Django_tables2 row?
Just need to define select = tables.CheckBoxColumn(accessor='pk') and it add the value as the record.id

Ember saving one to one, using promises

im trying to save a few models with one to one relation which initializes on a single controller action. Ive split things into small functions to use promises. I've been trying to make it work for almost a week and cant find the solution. I've also made a jsbin:
http://jsbin.com/enoYONAv/1/edit
Instead of valueBinding you can use selectionBinding in your Ember.Select, to retrieve the selected model directlly instead of your id. For example:
{{
view Ember.Select
prompt="Gender"
contentBinding="genders"
optionValuePath="content.id"
optionLabelPath="content.type"
selectionBinding="selectedGender"
}}
So in you action you can do:
var gender = this.get('selectedGender');
...
var hash = {
name : personName,
gender : gender,
organization : organization
};
this.savePerson(hash).then(this.saveAgentAssociation(agentAddress));
This is your updated jsbin please give a look http://jsbin.com/efeReDer/1/edit

Setting selected entry using helper.options?

Im am using Play 2.0.4 and
helper.options(myitems)
in my template (inside of a helper.select)
In this case, how can I define the default selected entry, which shall be one entry out of myitems? Thanks for any hint!
A little bit more about my case:
Imagine a news archive, showing all news titles. This news archive uses pagination, pagination uses GET to pass the next/previous page number.
The play framework however will only correctly select the currently selected "select" item (here: news category) when a POST request was used - while pagination uses GET!
Intended behaviour: While a filter is applied / a specific news category is selected, this shall always be visible to the user by preselecting the currently selected news category in the "select" form.
A "screenshot" for illustration:
So, anyone having a good idea on how to cope with this problem? Any way to tell Play manually which entry from the "select" form it shall select? '_default always adds a new entry instead of selecting one out of the given options ): Would be great, if one wouldn't have to build the complete "select" form manually.
Try passing '_default option to select helper:
#import views.html.helper._
#select(form("email"), options(List("first", "third")), '_default -> "second")
It seems, unfortunately, the only way to figure it out is to look up the source.
Update:
Specifying _default property doesn't set selected attribute on option tag. It looks like the only way to preselect entry is to pass prefilled form to the template. For example, suppose you have following form:
case class RegInfo(email: String, color: String)
private val registrationForm = Form(
mapping(
"email" → email,
"color" → nonEmptyText(minLength = 5, maxLength = 32)
)(RegInfo.apply)(RegInfo.unapply)
)
Then in the action prefill form before passing to the view:
def create = Action {
Ok(html.create(registrationForm.fill(RegInfo("user#qwe.com", "blue"))))
}
Then in template use helper:
#select(form("color"), options(List("red", "green", "blue")))
And value will be preselected.
Ended up with the pragmatic approach:
<select id="myfield" name="myfield" >
<option class="blank" value="">-- All items --</option>
#for((key, value) <- MyModel.options) {
#if(key == GETValuePassedToTemplate) {
<option value="#key" selected>#value</option>
} else {
<option value="#key">#value</option>
}
}
</select>
Still wondering if there is a better option / way to do it.
Actually, there is a nicer solution to it. If you call the template having the form partially bound you will achieve your goal. Here's the code for your controller:
Ok(views.html.myForm(myForm.bind(
Map("fieldName1" -> "value1",
"fieldName2" -> "value2"))))
Make sure you map fieldnames to the values of the options you want pre-selected.
Still wondering if there is a better option / way to do it.
Well, if your not hell-bent on using play to solve this particular problem, you could always solve it using JavaScript and jQuery:
$(function () {
$('#yourSelect_id').val(5);
}
Where your select options each has values and the one option you whish to pre select has value 5.