2

I'm using the Django Admin Site to manage my uploads. I would know if it's possible to set the original filename title as default title of an Image class.

Models.py:

class Multimedia(models.Model):
    id_multimedia = models.AutoField(primary_key=True)
    titulo = models.CharField(max_length=80, blank=True, null=True)
    descripcion = models.TextField(blank=True, help_text='Descríbeme...')
    path = models.FilePathField(path='media', allow_folders=True)
    album = models.ForeignKey(Album, on_delete=models.CASCADE)
    fecha_creacion = models.DateTimeField(auto_now_add=True)
    keyword = models.ManyToManyField('Keyword', help_text="Selecciona las palabras clave para etiquetar.")

    def __str__(self):
        return self.titulo


class Imagen(Multimedia):
    #titulo = models.CharField(max_length=100)
    image_width = models.PositiveSmallIntegerField(default=640)
    image_height = models.PositiveSmallIntegerField(default=480)
    fichero_imagen = models.ImageField(verbose_name='Archivo de imagen',
                                       upload_to='files/img',
                                       width_field='image_width',
                                       height_field='image_height')
    thumbnail = ImageSpecField(source='fichero_imagen',
                               processors=[ResizeToFill(600, 300)],
                               format='JPEG',
                               options={'quality': 60})

I want to upload an image and leave the title field blank instead of give a title. Then, set the Multimedia.titulo as the original upload filename. I have hear about prepopulated fields, but I don't know if it is possible. Thanks in advance.

Community
  • 1
  • 1
Antonio Maestre
  • 123
  • 4
  • 14

1 Answers1

0

I was doing something similar and I found that, as is explained here, when you upload a file, it is stored in the dict 'request.FILE', who returns UploadedFile objects. You can get the name of the file by accessing it's name attribute (request.FILE['YourModelImageField'].name).

You could have something like this:

#model.py
class YourModel(models.Model):
    name = models.CharField(max_length=20)
    image = models.ImageField() # In this case we will have request.FILE['image'].name

#forms.py
class YourModelForm(ModelForm):
    class Meta:
        model = YourModel
        fields = ['image'] 

#views.py
def add_model(request):
    form = YourModelForm(request.POST, request.FILES)
    uploaded_file=request.FILES
    if form.is_valid():
       model_instance = form.save(commit=False)
       model_instance.name=uploaded_file['image'].name
       model_instance.save()
       return render(request, context={'form': form})

I'm not really a django expert so if anyone can see an error or a better way to do it, please let me know. However this worked for me, I hope it can help you.

Laura
  • 1