This is my .html file. It enables the user to upload files and see the list of files uploaded, and download the files on the list -- or is supposed to!
The problem is that document.docfile.url (docfile is the FileField object) doesn't return the desired file path. The desired filepath contains 'media' but the returned file path is myapp/list/(...)
My MEDIA_URL is 'media', that is.
I suspect this is an inadequate explanation, so just let me know if you need further information.
<body>
<!-- List of uploaded documents -->
{% if documents %}
<ul>
{% for document in documents %}
<li>{{ document.docfile.name }}
Download</li>
{% endfor %}
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
<!-- Upload form. Note enctype attribute! -->
<form action="{% url "list" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
This is my views.py:
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('myapp.views.list'))
else:
form = DocumentForm() # An empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render_to_response(
'myapp/list.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
Related
I have created a django site, django site is working in this way. You go to the site, upload document with data and you get some results. You upload excel file, and you download excel file. In background I used pandas for calculations. In the end you can see code.
I have left one thing to finish. I want to create drag&drop for upload document. Chech picture 1, as I understand this is already drag&drop, just doesn't look as I would like to. I want to look like in picture 2.
Picture 1: Current
Picture 2: I would like to look like this.
Can I change the look that you seen on first image without using js?
This is html that I have and output is shown in picture 1...
{% extends "base.html" %}
{% load static %}
{% block content %}
<form action="{% url "cal" %}" method="post" enctype="multipart/form-data" class="dropzone">
{% csrf_token %}
{{ message }}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload and Download!"/></p>
</form>
{% endblock content %}
This is function in views
def OnlyCAL(request):
if request.method == "POST":
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
output = io.BytesIO()
newdoc = request.FILES['docfile']
#pandas calculations
response = HttpResponse(
output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
else:
form = DocumentForm()
return render(request, 'cal.html', { 'form': form, 'page_title':page_title })
I think the best option for you is to use dropzone.js. You can find documentation here.
You should include .js and .css. Also you can customize dropzone view on your own as described here (example of customizing dropzone in combination with Django, maybe will be useful for you)
You can try this (.js and .css files included directly in your template just for example, you can include easily include it in other way):
{% extends "base.html" %}
{% load static %}
<script src="https://unpkg.com/dropzone#5/dist/min/dropzone.min.js"</script>
<link rel="stylesheet" href="https://unpkg.com/dropzone#5/dist/min/dropzone.min.css" type="text/css" />
{% block content %}
<form id="dropZoneForm" action="{% url "cal" %}" method="post" enctype="multipart/form-data" class="dropzone needsclick dz-clickable">
{% csrf_token %}
<input type="hidden" name="abc" value="i am hidden value">
<div class="fallback">
<input name="file" type="file"/>
</div>
<input type="submit" id="submit-all" value="Upload and Download" class="custom-button" style="float: right">
</form>
{% endblock content %}
I have been trying to implement a way to post a project post where the user can upload multiple images. The multiple image upload works but posting the post itself does not work.
I am not sure what to do with the project_form.
It is not valid even tho the fields have correct values.
My code is:
views.py
class CreateProjectsView(View):
def get(self, request):
p_photos = P_Images.objects.all()
#project_form = ProjectsForm(initial=self.initial)
project_form = ProjectsForm
context = {
'p_photos': p_photos,
'project_form': project_form,
}
return render(self.request, 'projects/forms.html', context)
def post(self, request):
project_form = ProjectsForm(request.POST or None, request.FILES or None)
p_formset = P_ImageForm(request.POST, request.FILES)
# Checks if the project_form is valid before save
if project_form.is_valid():
instance = project_form.save(commit=False)
instance.user = request.user
instance.save()
# Checks if multiple image upload is valid before save
if p_formset.is_valid():
#if project_form.is_valid() and p_formset.is_valid():
#instance = project_form.save(commit=False)
#instance.user = request.user
#instance.save()
images = p_formset.save(commit=False)
images.save()
data = {
'is_valid': True,
'name': images.p_file.name,
'url': images.p_file.url
}
else:
data = {
'is_valid': False,
}
return JsonResponse(data)
forms.html
<form action="{% url 'create_post:retrieve_projects' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{% for hidden in project_form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in project_form %}
{{ field.errors }}
{{ field }} <br />
{% endfor %}
<input type="submit" value="OK">
</form>
If the form is not valid, you should provide a way for the user to correct their errors and resubmit the form. Perhaps something like this:
if project_form.is_valid():
instance = project_form.save(commit=False)
instance.user = request.user
instance.save()
else:
return render(request, 'project_form.html', {'form': project_form})
So I actually found a fix for this.
The issue is in the forms.html
I changed the "create_post:retrieve_projects" to "create_post:create_projects" in my form section.
forms.html
<form action="{% url 'create_post:create_projects' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{% for hidden in project_form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in project_form %}
{{ field.errors }}
{{ field }} <br />
{% endfor %}
<input type="submit" value="OK">
</form>
I'm trying to get the users input and add to a table in the database, everything goes smoothly with no errors .. but the input is not added to DB
urls.py
path('category/add/', views.add_cat, name="add_cat"),
view.py
def add_cat(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = CatForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
entry = Categories.objects.create(category_name=new_cat_name)
entry.save()
# ...
# redirect to a new URL:
return HttpResponseRedirect('/')
# if a GET (or any other method) we'll create a blank form
else:
form = CatForm()
return render(request, 'add_cat.html', {'form': form})
add_cat.html
{% extends 'base.html' %}
{% block content %}
{% load static %}
<form action="/" method="post">
{% csrf_token %}
{% for form in form %}
<h3 align="center">{{ form.label }}</h3>
<div align="center">{{ form }}</div>
<br>
<br>
{% endfor %}
<div align="center">
<input type="submit" class="btn btn-dark" style="width: 100px;"value="إضافة" />
</div>
</form>
{% endblock %}
{% extends 'base.html' %}
{% block content %}
{% load static %}
<form action="" method="post">
{% csrf_token %}
{% for form in form %}
<h3 align="center">{{ form.label }}</h3>
<div align="center">{{ form }}</div>
<br>
<br>
{% endfor %}
<div align="center">
<input type="submit" class="btn btn-dark" style="width: 100px;"value="إضافة" />
</div>
</form>
{% endblock %}
change your form action, you were posting the data to '/' url but you need to put it in your add view
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
My form inputs are not showing. It's just a button. i think homepage.html doesn't getting this form
Forms.py
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
Views.py
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'mainApp/homepage.html', {'form': form})
homepage.html
{% extends "mainApp/wrapper.html" %}
{% block title %}Главная{% endblock %}
{% block content %}
<h1>Main page</h1>
{% include "mainApp/includes/somehtml.html" %}
<br>
<form action="/account/username/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
<br>
{% endblock %}
It shoes only "Submit" button. How can I fix it?
Please change
{{form}}
to {{form.as_p}}
Views.py
from app_name.forms import * # Change app_name with your app name
def get_name(request):
temp_context = {} # Check here
if request.method == 'POST':
acc_form = NameForm(request.POST) # Check here
temp_context["acc_form"] = acc_form # Check here
if acc_form.is_valid(): # Check here
return HttpResponseRedirect('/')
else:
temp_context[“acc_form”] = NameForm() # Check here
return render(request, 'mainApp/homepage.html', temp_context) # Check here
homepage.html
{% extends "mainApp/wrapper.html" %}
{% block title %}Главная{% endblock %}
{% block content %}
<h1>Main page</h1>
{% include "mainApp/includes/somehtml.html" %}
<br>
<form action="/account/username/" method="post">
{% csrf_token %}
{{ acc_form }} # Check here;
# you can also try {{ acc_form.as_table }} or {{ acc_form.as_p }} if there any issue
<input type="submit" value="Submit" />
</form>
<br>
{% endblock %}
I just started on python / django and I was wondering if there was any way to play an uploaded mp3? I'm able to open an uploaded docx or txt file but with mp3s and playing them, I'm getting "Not Found: /list/03 The Forgotten.mp3", with 03 The Forgotten.mp3 being some random song I've uploaded.
Here's my views.py
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from docx import Document
from polls.models import Document
from polls.forms import DocumentForm
from django.http import HttpResponse
import docx2txt
def list(request):
# Handle file upload
context = {}
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = request.FILES['docfile']
#newdoc.save()
try:
name = newdoc.name
if name.endswith("docx"):
text = docx2txt.process(newdoc)
context["uploadedFile"] = text
elif name.endswith("txt"):
context["uploadedFile"] = newdoc.read()
elif name.endswith("mp3"):
context["sound"] = newdoc
context["uploadedFile"] = "enjoy!"
# Redirect to the document list after POST
#return HttpResponseRedirect(reverse('polls.views.list'))
#context["uploadedFile"] = newdoc.read()
except:
context["uploadedFile"] = "not a word doc"
return render_to_response('fileUploadPage.html', context)
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render_to_response(
'polls/list.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
and my html page, list.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Minimal Django File Upload Example</title>
</head>
<body>
<!-- List of uploaded documents -->
{% if documents %}
<ul>
{% for document in documents %}
<li>{{ document.docfile.name }}</li>
{% endfor %}
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
<!-- Upload form. Note enctype attribute! -->
<form action="{% url 'list' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
</html>
and finally my fileUploadPage.html
<div id="uploaded">
{{ uploadedFile }}
<audio id="Player" autoplay>
<source src= "{{sound}}" />
</audio>
</div>
my fileUploadPage is outside my apps folder inside template (templates/myapp/) it is instead just in templates (templates/)