1

I try to create a link to download a file in the admin but it does not work

my model

class Event(models.Model):
    ......
    file = models.FileField(_('fichier'), upload_to='medias',  null=True,  blank=True)

    def file_(self):
        if self.file:
            return "<a href='%s'>download</a>" % (self.file.url,)
        else:
            return "No attachment"

my admin :

class EventAdmin(admin.ModelAdmin):

list_display = ('title', 'start', 'end', 'user', 'fin', 'frequency', 'file_',)


fieldsets = (
    (None, {
        'fields': ('title','start', 'end', 'is_cancelled', 'calendar', 'user', 'description', ('frequency', 'fin' ), 'activated', 'file_',)
    }),

I get the error :

Exception Value:

'EventAdmin.fieldsets[0][1]['fields']' refers to field 'file_' that is missing from the form.

what is this problem ?

2 Answers 2

1

You should define your admin like this:

class EventAdmin(admin.ModelAdmin):

    list_display = ('title', 'start', 'end', 'user', 'fin', 'frequency', 'file_link',)


    fieldsets = (
    (None, {
        'fields': ('title','start', 'end', 'is_cancelled', 'calendar', 'user', 'description', ('frequency', 'fin' ), 'activated', 'file',)
    }),

    def file_link(self, obj):
        if obj.file:
            return "<a href='%s'>download</a>" % (obj.file.url,)
        else:
            return "No attachment"
Sign up to request clarification or add additional context in comments.

Comments

0

file_ is a function in your model. You can only show fields in a fieldset. A valid field would be file itself, but not the function file_.

I would also construct the HTML in your template and not in your model (I am not even sure if this is working what you have done so far).

Assuming you pass the object event with your view to your template. So you can use in your HTML template file:

{% if event.file %}
    <a href="{{ event.file.url }}">Download</a>
{% else %}
    No attachment
{% endif %}

2 Comments

I want to open the file only in the admin, not in a template
Oh okay, sorry, didn't know that. But one of your errors is caused by file_ which is not a field but a function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.