Roger
Roger

Reputation: 4797

Using custom forms in Django admin app

My Django based app maintains has a booking calendar which is modelled using two classes: Calendar and CalendarDay. Calendar is an aggregation of various model classes, amongst which is CalendarDay. CalendarDay is the actual "meat" and holds booking information.

In the admin app I want to display both model classes together as a calendar: x months in a row with each month formatted as a calendar month (days of the week along the top and the days of the month formatted per week).

As this is beyond the capabilities of the standard Django admin interface I'm looking into possibilities to implement this within the Admin interface using minimal modifications. So far I've come up with the following approach:

  1. Create a custom form class using the Django Forms API.

  2. Somehow register the custom form class in the admin app.

  3. Create a custom template to render the form to HTML.

  4. Somehow bind the custom form to the Calendar instance that is selected from the list display in the admin application. I know a form can be bound to data by passing a dictionary of data to its constructor however I'm not sure how to do this with admin forms.

My question: is this a feasible approach and, if so, how would I go about [2] and [4]?

Upvotes: 1

Views: 3247

Answers (1)

Roger
Roger

Reputation: 4797

It was actually much easier than I thought. I ended up implementing a custom widget based on this post together with a subclass of HTMLCalendar.

EDIT: Although the approach as described in this answer worked, I was not completely happy with the end result. It ended up being too much of a rather complex hack. I reworked the solution along the original train of thought as described in my question, which was easy as well:

  • I moved the change_form.html file as described here.
  • I modified that template and added a new block to include a template capable of rendering a booking calendar.
  • I subclassed Python's HTMLCalendar class so that it's capable of processing the CalendarDay objects of a Calendar model and generate the required CSS styles to display the various states of each day in the calendar.

Upon initial creation of a new Calendar, the template gracefully displays a message to the user that there are no CalendarDay objects yet.

The end result:

enter image description here

Upvotes: 4

Related Questions