Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store files in djangos array field

I'm playing around with django.contrib.postgres.fields.ArrayField in django 1.8 alpha and try using it with a file field.

Here's a post in a fictional forum:

# coding=utf-8
from backend.core.models import Team
from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.db.models import FileField


class Post(models.Model):

    title = models.CharField(max_length=256)
    content = models.TextField()

    team = models.ForeignKey(Team, related_name='posts')

    attachments = ArrayField(FileField(), null=True)

    def __str__(self):
        return self.title

The migration worked and everything is looking great.

However: Django Admin does not support this field.

How would I implement that in code, how can I store / add a new file to this array field and store it's reference in the database?

like image 558
shredding Avatar asked Feb 23 '15 16:02

shredding


1 Answers

Currently, I think the django.contrib.postgres.fields.ArrayField is in active development. The django.contrib package is new to django 1.8 (which is still in beta) so I think this functionality is too early to count on.

The text field you are seeing is meant to be a delimited string which is saved in the array. It kinda makes sense with an array of FileFields because the FileField saves a URL string and not a blob of the file (as far as I can tell).

A \d table gives the table information on that column as follows:

arrayexample=# \d example_post
Column      | Type                     | Modifiers
--------------------------------------------------
attachments | character varying(100)[] |

Currently the field you are seeing in admin is created from here. Notice it inherits from forms.CharField while a FileField uses forms.ClearableFileInput.

I don't think the functionality you are looking for currently exists in Django but I think it is feasible to build it. Personally, I would approach building it by subclassing the existing ArrayField and overriding the formfield to use my custom form_class to better handle an Array of FileFields.

I hope this helps, I also don't see any open pull requests for this feature.

like image 62
erik-e Avatar answered Oct 19 '22 09:10

erik-e