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!