save image in django python

2

Hi, I would like to know if I can and how to possibly save an image in a folder whose name is entered in the title of the same model, for example:

title ="animation"

image = this will be stored in uploads / animation /

class Imagen(models.Model):
"""Models add Imagen.

.. versionadded:: 3.0

"""
titulo = models.CharField(max_length=250)
imagen = models.FileField(upload_to='uploads/')

thanks

    
asked by NEFEGAGO 13.06.2018 в 17:01
source

2 answers

1

Try this idea, create a function that manages how the file is saved.

In your case it would be like this:

models.py

def cambiar_ruta_de_fichero(instance, filename):
    if os.path.isdir(os.path.join('uploads', instance.titulo)):
        pass
    else:
        os.mkdir(os.path.join('uploads', instance.titulo))
    return os.path.join('uploads', instance.titulo , filename)

class Imagen(models.Model):
    titulo = models.CharField(max_length=250)
    imagen = models.FileField(upload_to=cambiar_ruta_de_fichero)
    
answered by 13.06.2018 / 18:06
source
0

1.-Configure your settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

2.- Configure your urls.py file

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # tus urls
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

3.-Defining your models.py

from django.db import models

class Documento(models.Model):
    descripcion = models.CharField(max_length=255, blank=True)
    documento = models.FileField(upload_to='documentos/')
    subido_a = models.DateTimeField(auto_now_add=True)

4.-Defining your forms.py

from django import forms
import *.models 

class DocumentoForm(forms.ModelForm):
    class Meta:
        model = Documento
        fields = ('descripcion', 'documento', )

5.-Define your views.py

def mi_metodo(request):
    if request.method == 'POST':
        form = DocumentoForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('index')#redirigue a donde deseas
    else:
        form = DocumentoForm()
    return render(request, 'mi_template.html', {
        'form': form
    })

6.-your template.html

{% extends 'base.html' %}

{% block content %}
  <form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Subir</button>
  </form>

  <p><a href="{% url 'index' %}">Regresar</a></p>
{% endblock %}

This has been what has worked for me, of course it is not the only method you can do it without the FORMS, with AJAX, anyway ...

Note .-

upload_to='documentos/' here define where you want to save the load.

I hope I help you!

    
answered by 13.06.2018 в 20:11