Django-tables2 Row Selection - django

How do I select a row from a table generated from django-tables2? I'd prefer not to have to select a row by checking a checkbox cell (selection = tables.CheckBoxColumn(accessor='pk')) in the row.

Depending on what you want to do, you can format the cell as an href, so that the user clicks on it to get the appropriate action- or detail-view. You can accomplish this easily by defining a method on the model to return the appropriate text, including self.id or other row-identification from the instance.
Example:
class Customer( models.Model):
...
#property
def td_inspect(self):
dest = reverse('customers:detail', args=(self.id,) )
return format_html('<td><a class="NoUnderline AddWayBack style-inspect" href="{dest}">🔎 </a></td>', dest=dest ) # 1f50e is magnify glass
You can also work client-side using JQuery or suchlike, passing the necessary id information via something like <td data_id={id}...

Related

Is it possible to apply the primary key of the row as an id attribute to each <td> when using django-tables2?

With django-tables2, i am trying to set the id of each element of my model as an "attribute" of every single <td> corresponding to a specific <tr>.
I'm using a dict in the Column Attributes definition like so:
class MainTable(tables.Table):
id = tables.Column()
Client = tables.Column(attrs={'td': {
'data-name': 'Client',
'data-type': 'text',
'data-pk': lambda record: record.pk,
'data-url': 'path/to/url',
'data-placeholder': 'New Client',
'data-title': 'New Client' }})
Every attribute is applying correctly except the 'data-pk'. Is there a way to get the primary key inside the dict? Or any other way to set this attribute using django-tables2 ?
Currently, you cannot do that on columns, but you can on rows:
class Table(tables.Table):
class Meta:
row_attrs = {
'data-pk': lambda record: record.pk
}
Which might make more sense anyway, since a record is mapped to a row, not to a single table cell in a row.
I can see the use for computable attrs with arguments on table columns, so if you decide you need it, you are welcome to open a Pull request.

Updating derived values in SQLAlchemy

Usual sqlalchemy usage:
my_prop = Column("my_prop", Text)
I would like different semantics. Let's say an object has a set of fields (propA, propB, propC). I would like to maintain a database column which is derived from these fields (let's say, propA + propB + propC). I would like the column to be updated whenever any one of these set of fields is updated. Thank you.
Hybrid properties provide the functionality you are looking for. They allow you to write python properties that are usable in queries.
Here's how you might start if you wanted to have a name column and provide access to first and last name properties.
#hybrid_property
def first_name(self):
# get the first name from the name column
#first_name.setter
def first_name(self, value):
# update the name column with the first name replaced
#first_name.expression
def first_name(cls):
# return a sql expression that extracts the first name from the name column
# this is appropriate to be used in queries

Count only published videos

I have a Category model and Video model
Category:
name=Charfield()
Video:
name=CharField()
category=ManyToManyField()
is_live=BooleanField()
And I want to have the get all categories with a video count but I want to exclude videos who are not live.
This my start state:
Category.objects.annotate(video_count=Count('video'))
# I tried this but I'm not sure if this the right way
Category.objects.exclude(video__is_liive=False)
Any Ideas?
If you want to filter the field you are annotating, you need to use raw SQL as you can't do it through the ORM yet. I wrote a blog post about this:
http://timmyomahony.com/blog/filtering-annotations-django/
Your situation is a little more complicated as you have a M2M relationship which uses an intermediate table. You need something like the following which joins all 3 tables and counts only those that are marked is_live=True (this is totally untested so you will need to play around with it)
categories = Category.objects.all().extra(select = {
"video_count" : """
SELECT COUNT(*)
FROM myapp_videocategory
JOIN myapp_videocategory on myapp_videocategory.category_id = myapp_category.id
JOIN myapp_video on myapp_videocategory.video_id = myapp_video.id
WHERE myapp_video.is_live = True
"""
}).order_by("-live_video_count",)

How to create Dynamic action in APEX4.1 Tabular form

am Using Apex4.1,
in my application I have one Tabular form which has the following fields,
Emp_id
Emp_name
Dept_id
Here Emp_id is the Updatable column and it is a select list LOV and
Emp_name is a upadatable column,
Here what I need is,
If I select the Emp_id from the LOV ,the Emp_Name should be stored automatically based
on the value selected in EMP_ID,
In tabular form I could not create Dynamic action like creating in normal forms,
Can anyone help me in this issue?
Thank you.
APEX does not currently provide dynamic actions on tabular form items. Hopefully this may be addressed in APEX 4.2 but the Statement of Direction does not explicitly say so.
So for now if you need to do this you will have to write your own Javascript, using the unique IDs of the tabular form items to manipulate them (the IDs look like "fcc_rrrr" where "cc" is the column number and "rrrr" is the row number). See this SO q&q for sample Javascript code that uses these.
The Javascript you need to write is a little daunting (for a beginner), but one thing to note is that in your case you can avoid any need for using AJAX to get the employee name by embedding the name in the return value of the LOV something like this:
select emp_name d, emp_id||':'||emp_name r
from employee
order by 1
This way the return values will look like '123:John Smith'; your Javascript can parse this string and extract 'John Smith' and insert it into the emp_name item on the same row. Obviously you will also need to parse this string to obtain the emp_id value you will need when updating the database when the page is submitted.

Django: Deleting user selected entries from a database

I have a Django app that displays a list of rows in a table to the user. Each row maps to an entry in a database. I want to let the user select the rows they would like deleting by adding a checkbox to the end of each row and a delete button ( similar to how gmail lets you delete multiple mail messages). I can't quite figure out how to write the view in terms of finding out which rows were selected and how to map these to the IDs of the entries that need deleting from the database. A simple code snippet showing how to do this would be greatly appreciated.
UPDATE:
I've found this code snippet that I think should do the trick
You can use the CheckboxSelectMultiple widget to auto-generate the corresponding HTML code so you don't have to do it manually.
You can define your form like so:
class UsersForm(forms.Form):
users = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=[QuerySetIterator(Users.objects.all(), "", False)], label="")
Another advantage is that you also get validation for free.
Create a formset and pass can_delete = True to the constructor. Then, in the template,
{{formset}}