Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
danihodovic opened this issue Aug 27, 2020 · 3 comments
Open

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

danihodovic opened this issue Aug 27, 2020 · 3 comments

Comments

@danihodovic
Copy link

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
Copy link
Author

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
Copy link

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

@LianYangCn
Copy link

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants