django-attachments
django-attachments copied to clipboard
Set request.user as creator in django-admin.
I'm using django-attachments to upload files in django-admin.
class MyEntryOptions(admin.ModelAdmin):
inlines = (AttachmentInlines,)
Instead of manually specifying the creator I would like to automatically set it to request.user. How can I do that?
Temporary workaround
from attachments.admin import AttachmentInlines
class AttachmentInlinesWithoutCreator(AttachmentInlines):
fields = ('attachment_file',)
class MyAdmin(admin.ModelAdmin):
inlines = (AttachmentInlinesWithoutCreator,)
def save_related(self, request, form, formsets, change):
attachment_formset = formsets[0]
attachment_form = attachment_formset.forms.pop()
message = form.save()
attachment = Attachment(
object_id=message.uuid,
content_type=ContentType.objects.get_for_model(MarketingMessage),
attachment_file=attachment_form.cleaned_data['attachment_file'],
creator=request.user,
)
attachment.save()
super().save_related(request, form, formsets, change)
It seems that it can only solve the problem of adding and modifying, and there will be problems with deleting
worked flawlessly
from attachments.admin import AttachmentInlines
class AttachmentInlinesWithoutCreator(AttachmentInlines):
fields = ('attachment_file',)
def get_formset(self, request, obj=None, **kwargs):
formset = super().get_formset(request, obj, **kwargs)
formset.this_is_a_mark = True
return formset
class MyAdmin(admin.ModelAdmin):
inlines = (AttachmentInlinesWithoutCreator,)
def save_formset(self, request, form, formset, change):
if getattr(formset, 'this_is_a_mark', False):
for form in formset.forms:
# create
if not hasattr(form.instance, 'creator'):
form.instance.creator = request.user
super().save_formset(request, form, formset, change)