Как загрузить файлы через BSModalCreateView с помощью встроенного набора форм?
В настоящее время я пытаюсь загрузить файл в BSModalCreateView при использовании встроенного набора форм и сохранить его в папке для тестирования, которая имеет полные права на чтение/запись. При попытке распечатать, какой файл был загружен в класс InMemoryUploadedFile
, ничего не распечатывается.
Если я закомментирую функцию def get_success_url()
(views.py) для выброса ошибки, я увижу, что файл загружается в класс InMemoryUploadedFile
:
Я не уверен, что я упускаю что-то в функции def doc_valid()
(views.py) или что-то с моим набором встроенных форм. Любое руководство будет оценено по достоинству, спасибо!
base.py
MEDIA_ROOT = os.path.join('home/my-location/')
MEDIA_URL = 'media/'
Views.py
from datetime import datetime as dt
from django.urls import reverse
from bootstrap_modal_forms.generic import (
BSModalCreateView
)
from users.forms.documents import DocumentForm, DocumentFormSet
from users.models.documents import Document
from users.models.users import User
class DocumentCreateView(BSModalCreateView):
form_class = DocumentForm
template_name = 'partials/test.html'
success_message = 'Document added successfully'
def get_success_url(self):
return reverse('users:detail', args=[self.kwargs.get(self.slug_url_kwarg)])
def get_context_data(self, *args, **kwargs):
context = super(DocumentCreateView, self,).get_context_data(*args, **kwargs)
context['action'] = 'Upload'
context['object_type'] = 'a Document'
context['user_to_edit'] = User.objects.get(username=self.kwargs.get(self.slug_url_kwarg))
if self.request.POST:
context['docfiles'] = DocumentFormSet(self.request.POST, self.request.FILES, instance=self.object)
else:
context['docfiles'] = DocumentFormSet(instance=self.object, initial={'user': context['user_to_edit'].id})
return context
def doc_valid(self, request):
context = self.get_context_data()
form = context['docfiles']
self.object = form.save()
if request.method == 'POST':
form = DocumentFormSet(request.POST, request.FILES)
if form.is_valid():
form = Document(docfile=request.FILES['docfiles'])
form.save()
print(form)
return super(DocumentCreateView, self).form_valid(form)
forms.py
rom django.forms.models import inlineformset_factory
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Div, Field, HTML, Layout, Row
from ..models.documents import Document
from ..models.users import User
from django import forms
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ('user', 'document')
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(DocumentForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.layout = Layout(
Div(
Row(Div(Field('user', readonly='true'), css_class='col-lg-12')),
HTML('<hr>'),
Row(
Div('document', css_class='col-lg-6'),
),
)
)
DocumentFormSet = inlineformset_factory(
User,
Document,
fields=['user', 'document'],
exclude=[],
extra=0,
min_num=1,
can_delete=True
)
models.py
from django.db import models
from django.db.models import CASCADE, ForeignKey
from .users import User
class Document(models.Model):
document = models.FileField(upload_to='documents')
user = ForeignKey(User, null=True, blank=True, related_name='documents', on_delete=CASCADE)
class Meta:
verbose_name_plural = 'Documents'
test.html
{% load crispy_forms_tags %}
{% include 'blocks/styles.html' %}
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="modal-header">
<h5 class="modal-title">{{ action }} {{ object_type }}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{% crispy form %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<input class="btn btn-primary" type="submit" value="{{ action }}" />
</div>
</form>
{% include 'partials/init_js.html' %}