Save content of zip file in django - django

Good Day,
I would like to save the content of the zip file. My code works, but they save only the filename and not the content or actual files neither in the database nor the project.
I need to save in the database the content of each file. Can someone please help me to fix my error? My code looks like this:
uploaded_file, = request.FILES.getlist('document[]')
with zipfile.ZipFile(uploaded_file.file, mode="r") as archive:
for zippedFileName in archive.namelist():
newZipFile = UploadedFile(document= zippedFileName)
newZipFile.user= request.user
files = newZipFile.save()
success=True
return render(request, 'uploader/index.html', {'files': [uploaded_file]})

You have to save your zipfile on your filesystemstorage : https://docs.djangoproject.com/fr/4.1/ref/files/storage/
Or you can use a BinaryField in your models and try to save your zipfile as encoded binary : https://docs.djangoproject.com/fr/4.1/ref/models/fields/#binaryfield
THe better way is clearly the usage of a FS i think

For people looking on how to save the content of a zip file, this solution works for me
IMAGE_FILE_TYPES = ['png', 'jpg', 'jpeg']
def PostCreate(request):
form = PostForm()
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid():
user_pr = form.save(commit=False)
user_pr.album_image = request.FILES['album_image']
with zipfile.ZipFile(user_pr.album_image, mode="r") as archive:
for fileName in archive.namelist():
file_type = fileName.split('.')[-1]
file_type = file_type.lower()
if file_type not in IMAGE_FILE_TYPES:
print("ERROR!!!")
else:
file= archive.extract(fileName, settings.MEDIA_ROOT + 'UnzippedFiles')
rbe = Post.objects.create(album_image=file)
rbe.save()
print("SUCESS!!!")
return render(request, 'photos/post.html', {'user_pr': user_pr})
context = {"form": form,}
return render(request, 'photos/post_form.html', context)

Related

How to make files available download in Django

This is my model
class UploadAssignment(models.Model):
doc=models.FileField()
assignment = models.ForeignKey(AssignAssignment, on_delete=models.CASCADE)
student= models.ForeignKey(Student, on_delete=models.CASCADE)
This is my view to upload.
def upload_assignment(request,pk):
student = get_object_or_404(Student,user_id=request.user)
assign = get_object_or_404(AssignAssignment, pk=pk)
if request.method == 'POST':
form = AssignmentUpload(request.POST, request.FILES)
if form.is_valid():
m=form.save(commit=False)
m.student_id=student.user_id
m.assignment_id=assign.pk
print(m)
m.save()
messages.success(request, 'Assignment upload is successful')
return redirect('home')
else:
form = AssignmentUpload()
return render(request, 'accounts/students/uploadassignments.html', {
'form': form
})
I'd like to write a view function for lecturer to download those files with upload assignment primary key. Any one have any idea?
Based on similar questions (this and this) and the docs you could try:
def download_file(request, pk):
obj = get_object_or_404(UploadAssignment, pk=pk)
response = HttpResponse(
obj.doc,
content_type='application/whatever-the-correct-type-is')
response['Content-Disposition'] = 'attachment; filename="foo.xls"'
return response
Content types and file extensions are always a tricky part with user-submitted files, since there are a lot of thinks that could go wrong or be attack vectors.
Read more: django user-uploaded-content-security.
You could also look into the special FileResponse class.

HOw to send data and file from a form using flask?

i have created a form using html and flask. where user will fill his name , address and other information , and will also upload his photo and other documents. once the user will fill the information and submits the form he will be redirected to another page with his own filled information and photo on the page.
i am able to get user information filled and redirect him to another page "apply.html" but when i am trying to upload photo. it's able to upload pic but do not redirect me to "apply.html"
in my routes.py
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
#app.route('/form.html', methods=['POST'])
def upload_file():
nform = NewRegistration(request.form)
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
#app.route('/form.html', methods=['GET', 'POST'])
def form():
nform = NewRegistration(request.form)
if request.method == 'POST':
if nform.validate() == False:
flash('All fields are required.')
return render_template('form.html', form=nform)
else:
post = request.form['element_15'].strip()
name = request.form['element_1_1'].strip()
last = request.form['element_1_2'].strip()
Name = str(name)+ ' ' +str(last)
father = request.form['element_2'].strip()
mother = request.form['element_3'].strip()
gender = request.form['element_17'].strip()
data = {'Name' : Name, 'post' : post, 'father' : father}
return render_template("apply.html", data=data)
elif request.method == 'GET':
return render_template('form.html', form=nform)
i know the problem is because of two function "upload_file" and "form" so suggest me the best way to get information and photo and also be able to redirect user to apply.html
Becuase you need to add render_template() in
#app.route('/form.html', methods=['POST'])
def upload_file():
// do something
render_template("yourpage.html")
Every route must return a response.
Also I would recommend use the same route for saving file+form.
#app.route('/form.html', methods=['GET', 'POST'])
def form():
nform = NewRegistration(request.form)
if request.method == 'POST':
if nform.validate() == False:
flash('All fields are required.')
return render_template('form.html', form=nform)
else:
try:
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
except Exception as e:
print "Form without file "+e
post = request.form['element_15'].strip()
name = request.form['element_1_1'].strip()
last = request.form['element_1_2'].strip()
Name = str(name)+ ' ' +str(last)
father = request.form['element_2'].strip()
mother = request.form['element_3'].strip()
gender = request.form['element_17'].strip()
data = {'Name' : Name, 'post' : post, 'father' : father}
return render_template("apply.html", data=data)
elif request.method == 'GET':
return render_template('form.html', form=nform)
Let me know if this helps.

Image upload in Django no error

Trying to save images to a specific folder in django. I get no error but the file doesn't show up where its supposed to.
Here is the model:
class FileUploadHandler(models.Model):
title = models.CharField(max_length=100)
file = models.ImageField(upload_to='/wiki/static/')
View:
def image_upload(request):
if request.method == 'POST':
form = UploadImageForm(request.POST, request.FILES)
if form.is_valid():
FileUploadHandler(request.FILES['image'])
form.save
return render_to_response('wiki/gallery.html')
else:
form = UploadImageForm()
return render_to_response('wiki/gallery.html', RequestContext(request, {'form': form}))
Totally stumped since I don't get an error.
don't you need parenthesis at the end of form.save,
i.e. form.save()
FileUploadHandler.objects.create(file=request.FILES['image'])
https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.create
https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#handling-uploaded-files

File Uploading Using Django

i'm new in django and i have a problem with Uploading File Please Help me!! :X
here is my view.py
def uploadimg(request):
try:
user = request.session['user']
if request.method == 'POST':
form = User_image_form(request.POST, request.FILES)
#if form.is_valid():
usr_img = User_image(imgfile = request.FILES['imgfile'])
return HttpResponse("yes")
#usr_img.user = user
usr_img.save()
return HttpResponse("yees the first upload is right !! :X")
else:
return HttpResponse("Noooooo!!!")
except:
pass
this is my form.py
class User_image_form(forms.Form):
imgfile = forms.FileField()
and this is my models.py
class User_image(models.Model):
imgfile = models.ImageField(upload_to = 'User-Image')
#user = models.ForeignKey(User_account)
and i have problem in view.py at line which
usr_img = User_image(imgfile = request.FILES['imgfile'])
and it's never get to the
return HttpResponse("Yes")
error:
Exception Value: The view User.views.uploadimg didn't return an HttpResponse object.
Plz Help
If there is an exception, you are not returning an HttpResponse object. Hence the error.
use form.is_valid() to see if the form is valid.
Something like this:
if request.method == 'POST':
form = User_image_form(request.POST, request.FILES)
if form.is_valid():
usr_img = User_image(imgfile = form.cleaned_data['imgfile'])
usr_img.user = user
usr_img.save()
return HttpResponse("yees the first upload is right !! :X")
else:
print form.errors #for debugging purposes only.
return HttpResponse("Noooooo!!!")

Django and xlrd, reading from memory

My plan is to let a user to upload an excel file, once uploaded I will be displaying editable form which contains the content of the uploaded excel, once user confirms the input is correct, he/she hits the save button and these items are saved at some model.
For this, I have written this view and form:
form:
IMPORT_FILE_TYPES = ['.xls', ]
class XlsInputForm(forms.Form):
input_excel = forms.FileField(required= True, label= u"Upload the Excel file to import to the system.")
def clean_input_excel(self):
input_excel = self.cleaned_data['input_excel']
extension = os.path.splitext( input_excel.name )[1]
if not (extension in IMPORT_FILE_TYPES):
raise forms.ValidationError( u'%s is not a valid excel file. Please make sure your input file is an excel file (Excel 2007 is NOT supported.' % extension )
else:
return input_excel
view:
def import_excel_view(request):
if request.method == 'POST':
form = XlsInputForm(request.POST, request.FILES)
if form.is_valid():
input_excel = request.FILES['input_excel']
# I need to open this input_excel with input_excel.open_workbook()
return render_to_response('import_excel.html', {'rows': rows})
else:
form = XlsInputForm()
return render_to_response('import_excel.html', {'form': form})
As you can see at the # I need to open this input_excel with input_excel.open_workbook() I need to read from memory but open_workbook reads from a file, without saving this input to somewhere, how can I read it ?
if form.is_valid():
input_excel = request.FILES['input_excel']
book = xlrd.open_workbook(file_contents=input_excel.read())
# your work with workbook 'book'
return render_to_response('import_excel.html', {'rows': rows})
When file_contents optional keyword is provided, filename keyword will not be used.
Happy Coding.