bartTC / django-attachments

A generic Django application to attach Files (Attachments) to any model.
BSD 3-Clause "New" or "Revised" License
296 stars 90 forks source link

Set request.user as creator in django-admin. #77

Open danihodovic opened 4 years ago

danihodovic commented 4 years ago

I'm using django-attachments to upload files in django-admin.

class MyEntryOptions(admin.ModelAdmin):
    inlines = (AttachmentInlines,)

image

Instead of manually specifying the creator I would like to automatically set it to request.user. How can I do that?

danihodovic commented 4 years ago

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)
LianYangCn commented 1 year ago

It seems that it can only solve the problem of adding and modifying, and there will be problems with deleting

LianYangCn commented 1 year ago

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)