views:

407

answers:

1

I have model for example like this:

class Meeting(models.Model):
    date = models.DateTimeField(default=datetime.datetime.now)
    team = models.CharField(max_length=100)

    class Meta:
        verbose_name_plural = u'Meetings'
        ordering = ['-date', 'team']

    def __unicode__(self):
        return u'%s %s' % (self.date, self.team)


class Entry(models.Model):
    meeting = models.ForeignKey(Meeting, blank=True)
    meeting_date = models.DateField(null=True)
    description = models.TextField()

    class Meta:
        verbose_name_plural = u'Entries'

    def __unicode__(self):
        return self.title

I am having a form I am controlling the input with

class MyEntryAdminForm(forms.ModelForm):
class Meta:
    model = Entry

I am getting the data for the meeting field with

meeting = forms.ModelChoiceField(queryset=Meeting.objects.all(), empty_label=None)

I want to extract the date part of the meeting field (I am able to manage this). This date part should be the input for the meeting_date field. The meeting_date field has no input field in the form and should be populated automatically. I don't know how to get this date extract into the meeting_date field and how to store it

The attempt in def clean(self)

cleaned_data['meeting_date'] = date_extract_from_meeting

does not work

Any help is highly appreciated

+4  A: 

There is probably a way to override the form save() method and put the date in at that step, but I can't find any examples of doing this.

A way that I know would work for sure is to pass in commit=False to form.save (this way the actual database insert doesn't happen yet):

instance = form.save(commit=False)

Then you can set the meeting date and save the object:

instance.meeting_date = instance.meeting.date
instance.save()

Hope this helps.

Ricky
+1: I think this is one of the reasons why commmit=False is present in Django.
S.Lott
Looks good but I am still lost. Where is this located at. Is it in the MyEntryAdminForm(forms.ModelForm): or somehow in the class EntryAdmin(admin.ModelAdmin):
Helmut
I got it: def save_model(self, request, obj, form, change): obj.meeting_date = str(obj.meeting)[0:16] obj.save()That works. Thanks for your help
Helmut
cool, glad I could help!
Ricky