after uploading a file in Django Firebase "Storage", how can I download that file by clicking the HTML button? - django

when I upload any type of file by clicking the "Send" button, that file will be uploaded, and get the URL of that file. then renders the URL through the context in HTML. But here, my problem is when I click the "Download" button the file opens up in that tab instead of being downloaded. How can I solve this?
Where I am use python-pip Pyrebase4==4.6.0
Firebase Connection
class Firebase:
def __init__(self):
firebaseConfig = {
'apiKey': "_____",
'authDomain': "____",
'projectId': "___",
'storageBucket': "_____",
'messagingSenderId': "______",
'appId': "___________",
'measurementId': "_______",
'databaseURL': '__________',
'serviceAccount': 'service.json'
}
firebase = pyrebase.initialize_app(firebaseConfig)
self.fireStorage = firebase.storage()
My Views
from django.shortcuts import render
from django.core.files.storage import default_storage
from . models import Firebase
def index(request):
if request.method == 'POST':
file = request.FILES['file']
file_save = default_storage.save(file.name, file) # save the file as temporary
firebaseObj = Firebase()
firebaseObj.fireStorage.child(f'files/{file.name}').put(f'medias/{file.name}')
URL = firebaseObj.fireStorage.child(f'files/{file.name}').get_url(None)
delete = default_storage.delete(file.name) # delete the temporary file
return render(request, 'index.html', context={'fileurl':URL})
return render(request, 'index.html')
In HTML
<div>
<form method="post" action="{% url 'index' %}" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="file" id="fileid" required> <br>
<button type="submit">Send</button>
</form>
<a href="{{ url }}" download> <button> Download Now </button> </a>
</div>

Related

Reading uploaded csv file into pandas dataframe

I am uploading a CSV file and wish to load it into a pandas dataframe. I have a problem loading the file into my view. The warning message is sent to the template which signifies that the file was not sent to the view.
Here is my view:
def showReadUploadedView(request, **kwargs):
context = {}
test_file = request.GET.get(u'testFile')
df = pd.read_csv(test_file)
context = {'df': df}
if not test_file:
messages.warning(request, f'No file to process! Please upload a file to process.')
return render(request, 'tasks/up_load.html', context)
Here is my template:
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" class="form-control-file mt-1 mb-1" id="testFile">
<button class="btn btn-danger btn-sm mb-3 mt-1" type="submit">Process this</button>
<a href="{% url 'upload-task' task.id %}" class="btn btn-danger btn-sm mb-3 mt-1">Process Data</
</form>
Since the data is being sent by the POST method (as defined on your form), there won't be anything in request.GET. However, since it is a file input, it also won't be in request.POST either. Django handles files specially and puts them in request.FILES.
def showReadUploadedView(request, **kwargs):
context = {}
if request.method == 'POST':
test_file = request.FILES.get(u'testFile')
if test_file:
df = pd.read_csv(test_file)
context['df'] = df
else:
messages.warning(request, f'No file to process! Please upload a file to process.')
return render(request, 'tasks/up_load.html', context)
https://docs.djangoproject.com/en/2.2/topics/http/file-uploads/

How to bookmark a page in Django?

I am trying to edit an html page so a logged in user can favorite / bookmark a video.id
Here is the .html file
<td>
<form method='POST' action="{% url 'researcher_view_app:favourite_post' video.id %}">
{% csrf_token %}
<input type='hidden' name='video' value={{ video.id }}>
<button type='submit'>Bookmark</button>
</form>
</td>
Here is the urls.py file
path('<int:fav_id>/favourite_post', views.favourite_post, name='favourite_post'),
Here is the view.py file
def favourite_post(request, fav_id):
video = get_object_or_404(Video, id=fav_id)
if request.method == 'POST':
video.
return render(request, 'researcher_view_app/%s' % fav_id)
First you modify the models.py that has the user models
class ProjectUser(AbstractUser):
images = models.ManyToManyField(Images)
def __str__(self):
return self.email
In the .html file add the following:
{% for image in available_images %}
/* show image */
<form method='post' action="{% url 'user-image-add' %}">
{% csrf_token %}
<input type='hidden' name='image' value={{image.id}}>
<button type='submit'>bookmark</button>
</form>
{% endfor %}
In your views.py add the following method
def user_image_add(request):
user_image_form = ImageForm(request.POST or None)
if request.method == 'POST' and user_image_form.is_valid():
request.user.images.add(user_image_form.cleaned_data['image'])
return JsonResponse(status=200)
raise Http404()
Create a forms.py file in your add and add the following:
class ImageForm(forms.Form):
image = forms.ModelChoiceField(queryset=Images.objects.all())
To show those bookmarked images you can just iterate over request.user.images (it gives you a QS of Images) similar to code above.
In the urls.py add the following:
path('user-image-add/', views.user_image_add, 'user-image-add')
In models.py add a method in User model for getting bool if video is bookmarked
def is_bookmarked(self, video_id):
return self.bookmarked_videos.filter(id=video_id).exists()
simirlarly is_bookmarked can be added to Video model accepting user_id and checking video.projectuser_set.
And add the following to your .html file where users bookmarked a video
`{% if video.is_bookmarked %}`
Delete the UserProfile as you do not need it. Just make sure to have needed instance in context of view.

Django Python uploading a file to a specific folder

I am working on a Django app and I want the users to be able to upload a csv file to a folder in the server. Appreciate if you could point me to the right direction.
You can just use the django FileField and that lets you upload the file to the specified folder directly through admin panel and same can be done using the form for normal user.
upload = models.FileField(upload_to='uploads/your-folder/')
Here is my complete solution
#view.py
def uploadfunc(request):
if request.method=='POST':
form =uploadfileform(request.POST,request.FILES)
if form.is_valid():
form.save()
return render_to_response('upload_successful.html')
else:
form=uploadfileform()
return render(request, 'upload.html',{'form':form})
#models.py
class uploadfolder(models.Model):
""" my application """
File_to_upload = models.FileField(upload_to='')
#forms.py
#uploading file form
class uploadfileform(forms.ModelForm):
class Meta:
model=uploadfolder
fields=('File_to_upload',)
#upload.html
<form method="post" action="{% url 'uploadfunc'%}" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_table }}
<!-- <button type="submit">Upload</button>-->
<input class="btn btn-primary btn-md" role="button" type="submit" name="submit" value="Upload File" >
</form>
#settings.py
MEDIA_ROOT = "/var/www/vmachines/registry/files/"
MEDIA_URL = "files/"
Clients can send files via multi-part requests. Following code demonstrates multi part requests using requests
import requests
url = "http://someurl"
files = {"file" : ("somename.txt", open("pathtofile", "rb"))}
requests.post(url, files=files)
This will give you an InMemoryFile in your server, which you can then save to your server using default_storage and ContentFile inbuilt in django
def filehandler(request):
incomingfile = request.FILES['file']
default_storage.save("pathtofolder", ContentFile(incomingfile.read()))

DJANGO - Redirect to different page with form data

Hi i want to redirect to a destination page with the from data. For example when user fills a form the data inputted in the form, i want that to be outputted on the destination page
my codes are as follows:-
source page(experiment.html), I am unsure what the action should be for the form so please help me with it
<form action="{% url 'lazer.views.about_experiment' exp.link_name %}" method="POST">
{% csrf_token %}
<label>Researcher Name(s):<input type="text" name="researcher">
<lable>Study Summary<textarea rows="10" cols="50" placeholder="here you go" maxlength="500" class="form-control" name="study"></textarea>
<br>
<input type = "submit" value="Submit" class="btn btn-primary" />
</form>
destination page (about_experiment.html)
<h3>Holding page for {{ exp.name }}.</h3>
<h2> {{ form }} </h2>
views.py
from .forms import AboutHelp
from django.shortcuts import render
from django.http import HttpResponseRedirect
def about_experiment(request):
if request.method == 'POST':
form = AboutHelp(request.POST)
if form.is_valid():
researcher = form.cleaned_data['researcher']
study = form.cleaned_data['study']
else:
form = AboutHelp()
return render(request, 'about_experiment.html', {'form': form})`
forms.py
from django import forms
class AboutHelp(forms.Form):
researcher = forms.CharField(max_length=100)
study = forms.CharField(max_length=500)
urls.py
url(r'^about/(?P<ex_link_name>\w+)', lazer.views.about_experiment, name='lazer.views.about_experiment'),

Trying to use django and dropzone/

I'm trying to use dropzone.js with django.
I'm following the somewhat dated guide here (https://amatellanes.wordpress.com/2013/11/05/dropzonejs-django-how-to-build-a-file-upload-form/)
I strongly suspect My view is at issue.
def test(request):
print "test view has been called"
if request.method == 'POST':
print "test request method is POST"
form = UploadFileForm(request.POST, request.FILES)
print request
print request.FILES
if form.is_valid():
new_file = AttachedFiles(attachedfile=request.FILES['file'])
new_file.save()
id = new_file.pk
print id
print "test form valid"
return HttpResponse(json.dumps({'id': id}), content_type="application/json")
print "test form not valid"
else:
form = UploadFileForm()
data = {'form': form}
return render_to_response('mediamanager/test.html', data, context_instance=RequestContext(request))
I've tested submitting to it with the dropzone code
<!-- IMPORTANT enctype attribute! -->
<form id="my_dropzone" class="dropzone" action="/mediamanager/test/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<button id="submit-all">
Submit all files
</button>
</form>
<script src="{% static 'dropzone/js/dropzone.js' %}"></script>
<script type="text/javascript">
Dropzone.options.myDropzone = {
// Prevents Dropzone from uploading dropped files immediately
autoProcessQueue : true,
init : function() {
var submitButton = document.querySelector("#submit-all")
myDropzone = this;
submitButton.addEventListener("click", function() {
myDropzone.processQueue();
// Tell Dropzone to process all queued files.
});
// You might want to show the submit button only when
// files are dropped here:
this.on("addedfile", function() {
// Show submit button here and/or inform user to click it.
console.log("blah")
});
}
};
</script>
and a basic form
<form action="{% url "test" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="file" />
<input type="submit" value="Submit">
</form>
And the form is never valid.
I'm using a modelform as suggested
class UploadFileForm(forms.ModelForm):
class Meta:
model = AttachedFiles
You can handle Dropzone posts like any other multipart form post.
Here's how I proceed:
#login_required
#usertype_required
def upload_picture(request, uid=None):
"""
Photo upload / dropzone handler
:param request:
:param uid: Optional picture UID when re-uploading a file.
:return:
"""
form = PhotoUploadForm(request.POST, request.FILES or None)
if form.is_valid():
pic = request.FILES['file']
# [...] Process whatever you do with that file there. I resize it, create thumbnails, etc.
# Get an instance of picture model (defined below)
picture = ...
picture.file = pic
picture.save()
return HttpResponse('Image upload succeeded.')
return HttpResponseBadRequest("Image upload form not valid.")
The form is dead simple
class PhotoUploadForm(forms.Form):
# Keep name to 'file' because that's what Dropzone is using
file = forms.ImageField(required=True)
In your model you need the upload_to set:
class Picture(models.Model):
[...]
# Original
file = models.ImageField(upload_to=get_upload_path)
And here's my upload path builder, but you can put anything
def get_upload_path(instance, filename):
""" creates unique-Path & filename for upload """
ext = filename.split('.')[-1]
filename = "%s.%s" % (instance.p_uid, ext)
d = datetime.date.today()
username = instance.author.username
#Create the directory structure
return os.path.join(
'userpics', username, d.strftime('%Y'), d.strftime('%m'), filename
)
Don't forget the csrf_token in the html form itself (I'm using an angularJS directive on top of it so will be different for you)
<form action="{% url 'upload_picture' %}" class="dropzone" drop-zone>
{% csrf_token %}
<div class="fallback">
<h3>Your browser is not supported.</h3>
<strong>
Click here for instructions on how to update it.
</strong>
<p>You can still try to upload your pictures through this form: </p>
<p>
<input name="file" type="file" multiple />
<input type="submit" value="Upload" />
</p>
</div>
</form>
I got dropzone js working by modifying the bootstrap example (I am using bootstrap) here: http://www.dropzonejs.com/bootstrap.html
I do not use any forms. I got a view handling the in coming ajax posts from dropzone. Here is the gist of my view code:
class AjaxUploadView(View):
"""
View for uploading via AJAX.
"""
def post_ajax(self, request, *args, **kwargs):
uploaded_file = request.FILES['file']
# Do stuff with file
# Return appropriate response
Hope it helps.