django tables2 create extra column with links - django

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.

Related

Flask WTForms - option_widget for SelectMultipleField?

I have a field in my Flask WTForm which uses a SelectMultipleField. I'm using a frontend library which renders the choices fine from the db and adds them to the input field as tags when I select them (like the tags do on this website when creating a question!).
However the data is not being saved, form.field.data and request.form.getlist('field') etc all show None. If I add option_widget=widgets.CheckboxInput to the SelectMultipleField, I can select and save data.
So what I'm wondering is, do I need make a custom field or widget in order for the form to use the selected options as the form data (for example, instead of checking if the field has been checked, it checks if it's in the input field). Going a bit mad reading all the documentation so grateful for a hint in the right direction! Code below:
field = SelectMultipleField(
"fieldname",
validators=[Optional()],
widget=widgets.ListWidget(prefix_label=False),
# option_widget=CheckboxInput(),
)
please try this way
from flask_appbuilder.fieldwidgets import Select2ManyWidget
"users": QuerySelectMultipleField(
_("group.user"),
query_factory=lambda: db.session.query(User),
widget=Select2ManyWidget(),
default=[],
),
The result will look like the image below

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: Generate form from dictionary

I'm currently working on a django-app where users have the option to select synonyms for a select number of words. These words are then replaced all over the website by these synonyms
these synonymes are defined as a separate model:
class TransportSynonyms(models.Model):
user= models.ForeignKey(user)
key = models.CharField(max_length=255)
value = models.CharField(max_length=255)
This process is done in part with template tags, and as such the number of words that can be 'synonymed' is limited. For example, the following words can be replaced by synonymes:
'train', 'plane'.
And appear like so in the html template:
{% get_trans "train" %}
{% get_trans "plane" %}
I now want to give user the ability to define synonymes for themselves, without the admin view. I created a few pages using a ListView as an overview (so the users could see which words they can change) with individual buttons that led to EditViews.
However, I'm since user have no synonyms linked to them by default, the ListView appears empty. I could solve that by passing a list from the view, but that list wont have the required '.id' values and would be worthless for linking to the EditViews.
My listview currently looks like the following table:
Original | Synonym
---------------------------
train | train (button to editview)
plane | aircraft (button to editview)
The buttons require an ID value
href="{% url 'synonym_edit' pk=synonym.id %}"
I have to find a way to fill the ListView with the 'synonymable' words and provide links to a DetailView (for synonyms might not yet exist).
I thought about dropping the ListView all together and instead pass a dictionary to a form. By default both the key and the value will be the same word
({'train' : 'train', 'plane' : 'plane'})
and a form would then be generated form this dictionary, allowing users to change the value by having the dictionary value be shown as a text input.
Its a bit more limited (and more cumbersome) than my original plan, but I think this might work. Problem is that I've only really worked with modelforms before, and I am currently stuck on having the form be generated from the dictionary. Could anyone here point me to the right direction?
Regards,
Jasper

Using jquery autocomplete Django form

I am using jquery autocomplete with my generic views on Django. I am getting the list via AJAX, but there is one problem. When the user get the category he wants, he will select that value. Thus, if I append the value on that field $("#id_category").val(ui.item.value); it will show the pk on that field instead of value, so if I append $("#id_category").val(ui.item.label); django will complain it should be the instance. Django is completely right. How to make this work?
Edit:
I have made id_category hidden field and added category_display to append the text value. It is working. But while editing the category_display would be empty. Again I am using generic view. How to solve this one on the edit?
I had similar issue and I suggest you to think about question: 'What will happen if user enters not valid category name(category with this name doesn`t exist)?'
if you need to accept entered value and add new category, you have to make clean_category method in form:
def clean_category(self):
name = self.data['category']
return Category.objects.get_or_create(name=name)[0]
and display ui.item.label for user
if new category isn`t acceptable you can raise error in clean_category method or use something like select2(http://ivaynberg.github.io/select2/) for your field. I choose second variant.

django tables2 checkbox

I'm new to programming so this may be a trivial question...
In django-tables2, I'd like to be able to display the column header name when using CheckBoxColumn. Right now, all the checkboxes are displaying for each row, including in the header. I don't mind having a checkbox in the header (I figure that would be a great way to do a "select all" in the long run), but I need the column name to display. Does anyone have a solution for this?
Create your own custom checkbox column class that inherits from tables.CheckBoxColumn
then override the render method, then specify the check box together with its label as html response.
class CustomCheckBoxColumn(tables.CheckBoxColumn):
def render(self, value, record, bound_column):
return mark_safe(u'column Name<input type=checkbox, … />')
Another option is to use the TemplateColumn() instead of CheckBoxColumn()
template = '<input type="checkbox" name="{{record.name}}" />'
checkbox_column_header = tables.TemplateColumn(template)