I am writing a django application, that stores and displays working hours of employees.
The problem is, that for example pediatrists have 2 types of working hours - separate for sick children and healthy ones.
So I thought, it would be cool, to use HTML table to display the hours for each employee. My idea was to have a "ListField" representing each row of table, with ForeignKey to employee. That way, admin could create lists like:
['', 'Sick Children', 'Healthy Children'],
['Monday', '8-12', '12-14'],
['Friday', '12-15']
And it would appear on website, as an HTML table, that would look pretty nice.
The thing is, I would love it to look easy and intuitive for an admin of website. So I would love to keep the table rows as inline of employee in admin panel.
So, I have created models:
class TableRow(models.Model):
employee = models.ForeignKey(Employee)
class TableCell(models.Model):
content = models.CharField(max_length=20)
row = models.ForeignKey(TableRow)
And tried stuff like:
class TableCellInline(admin.TabularInline):
model = TableCell
class TableRowInline(admin.TabularInline):
model = TableRow
class EmployeeAdmin(admin.ModelAdmin):
inlines = [TableRowInline]
admin.site.register(Employee, EmployeeAdmin)
admin.site.register(TableRow, TableRowAdmin)
Which doesn't work (as I expected, but didn't hurt to try). Admin panel shows an option to add table row, when adding/editing employee, but doesn't show any option to add any cell to the row.
Is there any way to allow adding the rows while editing/adding employee? Or maybe a totally different way to solve the problem?
What you're trying to do is commonly referred to as nested inlines. Unfortunately, I'm afraid this is still not supported by the admin. See the following resources for more information.
Nested inlines in the Django admin?
#9025 assigned New feature: Nested Inline Support in Admin
Related
Been searching the web for a couple hours now looking for a solution but nothing quite fits what I am looking for.
I have one model (simplified):
class SimpleModel(Model):
name = CharField('Name', unique=True)
date = DateField()
amount = FloatField()
I have two dates; date_one and date_two.
I would like a single queryset with a row for each name in the Model, with each row showing:
{'name': name, 'date_one': date_one, 'date_two': date_two, 'amount_one': amount_one, 'amount_two': amount_two, 'change': amount_two - amount_one}
Reason being I would like to be able to find the rank of amount_one, amount_two, and change, using sort or filters on that single queryset.
I know I could create a list of dictionaries from two separate querysets then sort on that and get the ranks from the index values ...
but perhaps nievely I feel like there should be a DB solution using one queryset that would be faster.
union seemed promising but you cannot perform some simple operations like filter after that
I think I could perhaps split name into its own Model and generate queryset with related fields, but I'd prefer not to change the schema at this stage. Also, I only have access to sqlite.
appreciate any help!
Your current model forces you to have ONE name associated with ONE date and ONE amount. Because name is unique=True, you literally cannot have two dates associated with the same name
So if you want to be able to have several dates/amounts associated with a name, there are several ways to proceed
Idea 1: If there will only be 2 dates and 2 amounts, simply add a second date field and a second amount field
Idea 2: If there can be an infinite number of days and amounts, you'll have to change your model to reflect it, by having :
A model for your names
A model for your days and amounts, with a foreign key to your names
Idea 3: You could keep the same model and simply remove the unique constraint, but that's a recipe for mistakes
Based on your choice, you'll then have several ways of querying what you need. It depends on your final model structure. The best way to go would be to create custom model methods that query the 2 dates/amount, format an array and return it
Say I have a model:
class Question(models.Model):
text = models.TextField(verbose_name=u'Вопрос', max_length=1024)
is_free_text = models.BooleanField(verbose_name=u'Ответ в виде текста?')
sort_order = models.PositiveSmallIntegerField()
is there a plugin or something for django admin to have list of models somewhere and move them up and down (or drag and drop) to define their sort order? I basically want every question to have a unique sort order so that they are sorted according to their sort_order where fetched.
There are lots of options but you will most likely have to tinker a bit with them. Here are some snippets (I'm not sure how well these will work):
http://djangosnippets.org/snippets/2306/
http://djangosnippets.org/snippets/2047/
http://djangosnippets.org/snippets/2057/
Some apps that claim to do it:
https://github.com/ff0000/django-sortable
https://github.com/centralniak/django-inline-ordering
If you are interested installing django-grapelli (which is a skin for the entire django admin) , you can make use of their sortable change list items
after wracking my brain for days, I just hope someone can point me to the right approach.
I have 4 Models: Page, Element, Style and Post.
Here is my simplyfied models.py/admin.py excerpt: http://pastebin.com/uSHrG0p2
In 2 sentences:
A Element references 1 Style and 1 Post (2 FKs).
A Page can reference many Elements, Elements can be referenced by many pages (M2M).
On the admin site for Page instances I included the M2M relation as 'inline'. So that I have multiple rows to select Element-instances.
One row looking like: [My Post A with My Style X][V]
What I want is to replace that one dropdown with 2 dropdowns. One with all instances of Post and one with all instances of Style (creating Element instances in-place). So that one row would look similar to the Element admin site: [My Post A][V] [My Style X][V]
Sounds easy, but I'm just completely lost after reading and experimenting for 2 days with ModelForms, ModelAdmins, Formsets, ... .
Can I do that without custom views/forms within the Django admin functionality?
One of my approaches was to access the Post/Style instances from a PageAdminForm like this, trying to create a form widget manually from it... but failed to do so:
p = Page.objects.get(pk=1)
f = PageAdminForm(instance=p)
f.base_fields['elements'].choices.queryset[0].post
Any advice or hint which way I need to go?
Thank you for your time!
I got exactly what I wanted after removing the M2M field and linking Elements to a Page with a 3rd ForeignKey in Element:
class Element(models.Model):
page = models.ForeignKey(Page)
post = models.ForeignKey(Post)
style = models.ForeignKey(Style)
Actually a non-M2M link makes more sense for my application after all.
Memo to self: Rethink model relations before trying to outsmart Django :-(
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}}
Creating an app to track time off accrual. Users have days and days have types like "Vacation" or "Sick"
Models:
DayType
Name
UserDay
Date
DayType (fk to DayType)
Value (+ for accrual, - for day taken)
Note
Total
I'm trying to generate the following resultset expanding the daytypes across columns. Is this possible in the ORM, or do I have to build this in code?
I think you'd have an easier time by not putting the DayType in another model. Is there a specific reason you went that route?
If not, you should take a look at the choices attribute of Django's fields. Your code would look something like this:
class UserDay(models.Model):
DAY_TYPES = (
('vac', 'Vacation'),
('ill', 'Sick'),
)
day_type = models.CharField(max_length=3, choices=DAY_TYPES)
# Other fields here...
It seems like a somewhat cleaner solution since the types of days they have aren't likely to change very often. Plus, you can avoid a DB table and FK lookup by storing the values this way.