views:

278

answers:

2

I have two models, Event and Series, where each Event belongs to a Series. Most of the time, an Event's start_time is the same as its Series' default_time.

Here's a stripped down version of the models.

#models.py

class Series(models.Model):
    name = models.CharField(max_length=50)
    default_time = models.TimeField()

class Event(models.Model):
    name = models.CharField(max_length=50)
    date = models.DateField()
    start_time = models.TimeField()
    series = models.ForeignKey(Series)

I use inlines in the admin application, so that I can edit all the Events for a Series at once.

If a series has already been created, I want to prepopulate the start_time for each inline Event with the Series' default_time. So far, I have created a model admin form for Event, and used the initial option to prepopulate the time field with a fixed time.

#admin.py
...
import datetime

class OEventInlineAdminForm(forms.ModelForm):
    start_time = forms.TimeField(initial=datetime.time(18,30,00))
    class Meta:
        model = OEvent

class EventInline(admin.TabularInline):
    form = EventInlineAdminForm
    model = Event

class SeriesAdmin(admin.ModelAdmin):
    inlines = [EventInline,]

I am not sure how to proceed from here. Is it possible to extend the code, so that the initial value for the start_time field is the Series' default_time?

A: 

Even I need a solution of a similar kind of problem. Like if I select a series that series's default_time should be set to start_time initially. Can anybody please tell what is to be done at this point.

krishna
A: 

You could pre-populate the start time in the view:

def create_event(request):
    # I'm assuming that the series PK has been passed to the view 
    # through the URLConf as series_pk
    series = get_object_or_404(Series, pk=series_pk)
    form = YourForm(start_time = series.default_time)

    return render_to_response("your_template.html", {'form':form})

Probably not a great approach for the admin though.

Chris Lawlor