admin auto populate user field from request
I have made a django admin form to add a new field to the model and update a generic model, my code is below. Its all working perfectly accept for saving the current logged in user. In the save() method i cannot access request.user to populate created_by field.
class 开发者_开发知识库EventAdminForm(forms.ModelForm):
tag_it = forms.CharField(max_length=100)
class Meta:
model = Event
# Step 2: Override the constructor to manually set the form's latitude and
# longitude fields if a Location instance is passed into the form
def __init__(self, *args, **kwargs):
super(EventAdminForm, self).__init__(*args, **kwargs)
# Set the form fields based on the model object
if kwargs.has_key('instance'):
instance = kwargs['instance']
self.initial['tag_it'] = ', '.join([i.slug for i in instance.tags.all()])
def set_request(self, request):
self.request = request
# Step 3: Override the save method to manually set the model's latitude and
# longitude properties based on what was submitted from the form
def save(self, commit=True):
model = super(EventAdminForm, self).save(commit=False)
for i in self.cleaned_data['tag_it'].split(','):
model.tags.create(slug=i, created_by=User.objects.get(username='mazban'))
if commit:
model.save()
return model
class EventForm(admin.ModelAdmin):
exclude = ('published_by', 'published_at', 'updated_at', 'updated_by', )
form = EventAdminForm
Taking from @brandon response and your comment, you can mix them doing:
# admin.py
# don't override EventAdminForm's save(). Instead implement it here:
class EventAdmin(admin.ModelAdmin):
exclude = ('published_by', 'published_at', 'updated_at', 'updated_by', )
form = EventAdminForm
def save_model(self, request, obj, form, change):
obj.save()
obj.tags.all().delete()
for i in form.cleaned_data['tag_it'].split(','):
obj.tags.create(slug=i, created_by=request.user)
To get access to the request in admin, you need to override the save_model method of your ModelAdmin:
Example:
def save_model(self, request, obj, form, change):
if not change:
obj.author = request.user
obj.save()
For more information, check the docs: https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#modeladmin-methods
精彩评论