Helmut
Helmut

Reputation: 232

How to store data in Django Model without having an input field

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

Upvotes: 2

Views: 3800

Answers (1)

Ricky
Ricky

Reputation: 5377

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.

Upvotes: 7

Related Questions