Can you see is there any problem? I don't have any errors, everything is showing but when I upload document, nothing happens, document is not uploaded. Everything seems as it should be, but something I missed, why won't upload document?
my_app/forms.py
class UploadFileForm(forms.Form):
file = forms.FileField()
my_app/hendle_file.py
def handle_uploaded_file(f):
with open('my_app/static/upload/'+f.name, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
my_app/views.py
from .forms import UploadFileForm
from .handle_file import handle_uploaded_file
def upload_file(request):
form = UploadFileForm()
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
print(form.cleaned_data)
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('file uploaded')
else:
form = UploadFileForm()
return render(request, 'my_app/uploadfile.html', {'form': form})
my_app/template/my_app/uploadfile.html
{% extends "my_app/base.html" %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<h1>Upload your document!</h1>
{{ form.as_p }}
<input type="submit" type="button" value="Upload"
</form>
{% endblock content %}
To upload a file within a form the enctype attribute has to be set to multipart/form-data
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<h1>Upload your document!</h1>
{{ form.as_p }}
<input type="submit" type="button" value="Upload"
</form>
Related
i've managed how to display a list of determined forms, without using formsets. But now i'm strugling to save the data from the form.
This is my template:
{% extends 'base.html' %}
{% block main %}
<div class="container">
<div class="container-form">
<form method="POST" enctype="multipart/form-data" action="{% url 'adjust_values' contract.id %}">
{% csrf_token %}
{% for form in items_forms %}
{{ form }}
{% endfor %}
<button type="submit" class="btn-confirm">Confirm</button>
</form>
</div>
<div class="container-descript">
<h2 class="h2-containter">Adjust your prices!</h2>
<img src="https://i.ibb.co/pX0bq35/Illustration.png" class="img-form">
</div>
</div>
{% endblock %}
This is my views.py
#login_required
def adjust_values(request, id):
contract = get_object_or_404(ClientContract.objects.filter(user=request.user), pk=id)
contract_items = contract.items.all()
items_forms = []
for item in contract_items:
items_forms.append(
ItemForm(request.POST or None, instance=item)
)
my_forms = all([form.is_valid() for form in items_forms])
form = ItemForm()
if my_forms and form.is_valid():
for form in items_forms:
form.save(commit=False)
form.save()
else:
print(form.errors)
context = {'contract': contract, 'form':form, 'items_forms': items_forms}
return render(request, 'item_formset.html', context)
Now i really do not know what i need to do to save the data from the forms. Is there any way to save the data using this structure for iteration trough forms?
I have a function-based view that does not load the data that was inputted. The view does not throw any error at all. It just presents the form as a blank one.
urls.py
path('edit/<slug>/', editPost, name='edit'),
views.py
#login_required
def editPost(request, slug):
if request.method == 'POST':
post = get_object_or_404(Post, slug=slug)
form = PostForm(request.POST or None, request.FILES or None, instance=post)
if form.is_valid():
post.author = request.user.username
post.updated = True
form.save()
return redirect('dashboard')
else:
form = PostForm(request.POST, request.FILES, instance=post)
return render(request, 'edit_post.html', {'form': form})
template
<form class="dropdown-item" action="{% url 'edit' slug=post.slug %}" method="post">{% csrf_token %}
<input class="btn btn-sm" type="submit" value="Edit">
render form in template, using {{ form.as_p }}
<form class="dropdown-item" action="{% url 'edit' slug=post.slug %}" method="post">
{% csrf_token %}
<!-- render form here -->
{{ form.as_p }}
<input class="btn btn-sm" type="submit" value="Edit">
</form>
or loop through form fields as
<form class="dropdown-item" action="{% url 'edit' slug=post.slug %}" method="post">
{% csrf_token %}
<!-- render form here -->
{% for field in form %}
{{ field.label }}
{{ field }}
{{ field.error }}
{% endfor %}
<input class="btn btn-sm" type="submit" value="Edit">
</form>
#login_required
def editPost(request, slug):
post = get_object_or_404(Post, slug=slug)
if request.method == 'POST':
form = PostForm(request.POST or None, request.FILES or None, instance=post)
if form.is_valid():
post.author = request.user.username
post.updated = True
form.save()
return redirect('dashboard')
else:
form = PostForm(instance=post)
return render(request, 'edit_post.html', {'form': form})
Probably you have to do something like that, there is not any reason to pass request.POST and request.FILES when you don't have POST action in the view. In that way you just have to pass the post object that have all the related info.
And also you have to render your form in the following way:
<form class="dropdown-item" action="{% url 'edit' slug=post.slug %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<!-- render form here -->
{{ form.as_p }}
<input class="btn btn-sm" type="submit" value="Edit">
</form>
Notice that enctype="multipart/form-data" is mandatory 'cause you are dealing with files in your form elsewhere it won't work properly.
Also checkout where you have to put your post = get_object_or_404(Post, slug=slug) line, 'cause in thay way you can pass the object to whatever action that is being performing (POST or GET).
The form submits but immediately says this field is required... although it was filled out. What am I doing wrong
In my view:
def fileupload(request):
if request.user.is_authenticated and request.user.is_staff:
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES.getlist('file_field'))
return HttpResponseRedirect('/fileupload/')
else:
form = UploadFileForm()
return render(request, 'fileupload.j2.html', {'form': form})
return HttpResponseForbidden('<h1>403 Forbidden</h1>')
with this form:
class UploadFileForm(forms.Form):
kit_number = forms.CharField(label="Kit number", max_length=100, required=True, help_text='Required.')
file_field = forms.FileField(label='Upload kit result')
and template:
{% extends "menu.j2.html" %}
{% block content %}
{% if request.user.is_authenticated and request.user.is_staff %}
<h3>File upload</h3><br><br>
<form action="/fileupload/" method="post">
{% csrf_token %}
<div class="form-group">
<table>
{{ form.as_table() }}
</table>
</div>
<input id="button" class="btn" type="submit" value="Sent">
</form>
{% else %}
You are not authorized to see this page
{% endif %}
{% endblock %}
You forgot to set the form enctype.
<form action="/fileupload/" method="post" enctype="multipart/form-data">
I have tried numerous things. At one point my forms were loading and now they are't. I get the page to load, but the forms simply don't appear, the page is just my layout.html.
urls.py
url(r'^profile/passreset/$', views.passwordReset, name='passwordReset')
views.py
def passwordReset(request):
if request.method == 'POST':
form = PasswordChangeForm(request.POST, user=request.user)
if form.is_valid():
form.save()
return rediect('/account')
else:
form = PasswordChangeForm(user=request.user)
return render(request, 'posts/accounts/changepass.html', {'form': form})
changepass.html
{% extends 'posts/layout.html' %}
{% block head %}
<title>Change Password</title>
{% endblock %}
{% block content %}
<div class="containter">
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
</div>
{% endblock %}
Also another question now. I found out it is rendering the page posts/account.html (when I have specified another) why is that?
I try to use Django forms but I have problems displaying all the fields on my Template.
I have created a form in the form.py file as:
class UploadCSVForm(forms.Form):
title = forms.CharField(max_length=255, help_text="Please type here", required=True)
csv_load = forms.FileField()
In my corresponding view I import the form as:
from myproject.myapp.forms import UploadCSVForm
and then in the specific view function I render the form as;
if request.method == 'GET':
....
....
form = UploadCSVForm()
ctx['form'] = form
return render_to_response(template, RequestContext(request, ctx))
Last in my template I call the form as:
<form id="file-uploader" method="post" enctype="multipart/form-data" action="{% url "layer" %}">
<input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<button type="submit" id="upload-button" class="btn btn-danger">Upload</button>
</form>
I only get to see the csv_load but not the title.
What am I doing wrong here?