2

I need to save files, but the number of files is uncertain, and in one request I can add a file, then in another request post, I can add one more file ...

For this reason I thought that creating a JSONField type field could help me in this matter, but I don't know if it is possible and if it is possible I have no idea how to implement it in Django.

Here is an example of how I currently upload a single file to Django Model:

import uuid
import time

from users.models import User
from django.db import models


def upload_location(instance, filename):
    filebase, extension = filename.split('.')
    milliseconds = int(round(time.time() * 1000))

    return 'events/thumbnail_images/%s__%s__%s.%s' % (instance.user_id, instance.name, milliseconds, extension)


class Test(models.Model):
    id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False)
    image_link = models.FileField(upload_to=upload_location)

    user = models.ForeignKey(
        User,
        null=True,
        blank=False,
        on_delete=models.CASCADE
    )

As I'm using Postgres relational database, and I'm not sure how many files the user will want to save, I figured using JSONField, so that as the user adds files, the 'path+filename' is also added.

It's possible? How to make?

maistack123
  • 135
  • 10

2 Answers2

1

I suggest you to create a separate model Attachment and make the relation with this model by adding ForeignKey field To Attachment model or using ManyToManyField by desired model.

With this approach you can add many files to the desired model.

Here is an example of Attachment model:

import uuid
import time

from users.models import User
from django.db import models


def upload_location(instance, filename):
    filebase, extension = filename.split('.')
    milliseconds = int(round(time.time() * 1000))

    return 'events/thumbnail_images/%s__%s__%s.%s' % (instance.user_id, instance.name, milliseconds, extension)


class Test(models.Model):
    id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False)
    user = models.ForeignKey(User,null=True,blank=False,on_delete=models.CASCADE)


class Attachment(models.Model):
    # here is the relation
    test = models.ForeignKey(Test, on_delete=models.CASCADE)
    name = models.CharField(verbose_name="Attachment Name", max_length=255, null=True, blank=True)
    att_img = models.ImageField(
        upload_to=upload_location,
        verbose_name="Attach an Image",
        null=True, blank=True, max_length=255
    )
    att_file = models.FileField(
        upload_to=upload_location,
        verbose_name="Attach a File",
        null=True, blank=True, max_length=255
    )
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '%s - %s' % (self.name, self.test)
NKSM
  • 5,422
  • 4
  • 25
  • 38
0

For file i am just taking image as an example

  class ImageClass(models.Model):
  YourClassHere_FK_image  = models.ForeignKey(
        'YourClassHere', related_name='images', on_delete=models.CASCADE)
    title = models.CharField(max_length=200, blank=True)
    image = models.ImageField(upload_to=UploadedConfigPath_image, verbose_name='Image', null=True, blank=True, validators=[FileExtensionValidator(allowed_extensions=[
                              'jpg', 'png',  'jpeg', 'webp'])], help_text="Something related images")

Then in your forms.py file do something like this

class Mult_ImageForm(forms.Form):
multiple_images = forms.FileField(required=False, help_text='Select Multiple Images(jpg,png) for your Class if you want (Optional) Max:10',
                                  widget=forms.ClearableFileInput(attrs={'multiple': True, 'accept': 'image/*'}))

Then do the views.py

def post_create(request):

    mul_images_product      =       Mult_ImageForm(request.POST,request.FILES)


    if request.method == 'POST':
    Your code here

Also in your HTML you need to render this form as you said it could be requested again and again. This is the simplest way to do it as per my understanding. You can add as many files as you like just provide them same foreign key to your ImageClass model in your views :)

Sami Hassan
  • 105
  • 12