I want to upload multiple files through a ModelForm,with all files to be assigned to a file
field of the Model.I have gone through the docs and I saw an example on it and I ve implemented it here but I can only get my form to pick multiple files but only one get saved and assigned to files
field.Below are my codes
models.py
class Feed(models.Model):
user=models.ForeignKey(User,on_delete=models.CASCADE,related_name='feeds')
text=models.TextField(blank=False,max_length=500)
files = models.FileField(upload_to="files/%Y/%m/%d")
forms.py
class FeedForm(ModelForm):
class Meta:
model=Feed
fields=('text','auth','files')
widgets={"files":forms.FileInput(attrs={'id':'files','required':True,'multiple':True})}
and views.py
def post_feed(request):
form_class = FeedForm
if request.method == 'POST':
form = form_class(request.POST,request.FILES)
if form.is_valid():
feed = form.save(commit=False)
feed.user = User.objects.get(pk=1)
feed.pub_date=timezone.now()
#instance = Feed(files=request.FILES['files'])
# feed.files=request.FILES['files']
feed.save()
return redirect('home')
else:
form = form_class()
return render(request, 'post_feed.html', {'form': form,})
from django.views.generic.edit import FormView
from .forms import FeedForm
class FileFieldView(FormView):
form_class=FeedForm
template_name='post_feed.html'
'''success_url=??? #I dont know what to write here.I thought of putting this
render(request, 'post_feed.html', {'form': form,}) because I just want
to reload the page but it gave an error,so I removed it entirely.'''
def post_feed(self,request,*args,**kwargs):
form_class=self.get_form_class()
form=self.get_form(form_class)
filez=request.FILES.getlist('files')
if form.is_valid():
for f in filez:
f.save()
return self.form_valid(form)
else:
return self.form_invalid(form)
Kindly help me out,Thanks in advance.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…