Hi Matteius,
You must set blank=True in the model so that the form can be returned to you
with those fields empty and then you fill it in the save().
pub_date = models.DateTimeField(blank=True)
author = models.ForeignKey(User, blank=True, verbose_name='Author')
Also read up on editable=False
Regards
Chris
-----Original Message-----
From: [email protected] [mailto:[email protected]] On
Behalf Of Matteius
Sent: 17 February 2011 08:47
To: Django users
Subject: How to Auto fill fields on Save in Django Admin?
I have an Announcement model that has two fields I want to auto-fill
in when they are left blank (they are required fields with normal
defaults). I have the following Code (simplified data listing for
this post) ---- THe Problem is that when I go to save an Announement
in the admin with either of those fields blank it returns to the Add/
Edit Form with "This field is required." despite my code to try and
fill that in. Clearly I'm missing how to do this, any advice?
class Announcement(models.Model):
""" Represents an Announcement in the classcomm system. """
# Data Model Fields
pub_date = models.DateTimeField()
author = models.ForeignKey(User, verbose_name='Author')
def clean(self):
""" Implement auto fill pub_date. """
if not self.pub_date:
self.pub_date = datetime.today()
super(Announcement, self).clean()
# EndDef
def save(self):
""" Implement auto fill pub_date. """
if not self.pub_date:
self.pub_date = datetime.today()
super(Announcement, self).save()
# EndDef
# EndClass
Then in admin.py I have:
class AnnouncementAdmin(admin.ModelAdmin):
""" Admin customizations for Announcement Models. """
fieldsets = (
(None, {
'fields': ('headline', 'department', 'course', 'content')
}),
('Advanced options', {
'classes': ('collapse',),
'fields': ('author', 'pub_date', 'make_global')
}),
)
def save_model(self, request, obj, form, change):
""" Autofill in author when blank on save models. """
obj.author = request.user
obj.save()
# EndDef
def save_formset(self, request, form, formset, change):
""" Autofill in author when blank on save formsets. """
instances = formset.save(commit=False)
for instance in instances:
instance.author = request.user
instance.save()
formset.save_m2m()
# EndDef
# EndClass
Regards,
Matt
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.