Python - Two forms can't be saved separately - python

I am currently creating an upload function and I am having a hard time in saving the forms. Currently I have two separate forms, one for the profile detail and one for the upload picture only.
This is my views.py right now:
user = UserViewModel(username, profile)
# This method is to save the file to the directory
user.save_to_directory(userName, request.FILES['upload_picture'])
form = UserForm(request.POST)
if form.is_valid():
user.firstname = form.cleaned_data['firstname']
user.lastname = form.cleaned_data['lastname']
return render(request, 'profile.html',{'message':message})
else:
return render(request, 'profile.html',{'errorMessage':user.errorMessage})
This is my template:
<form name="upload_picture" id="upload_picture" accept-charset="utf-8" enctype="multipart/form-data" action="{% url 'actuser:profile' userName %}" method="post">
<input type="file" name="upload_picture"/>
</form>
<button type="button" onclick="document.getElementById('upload_picture').submit();">
Upload
</button>
<form name="update_profile" id="update_profile" action="{% url 'user:profile' userName %}" method="post">
firstname<input type="text" name="firstname">
lastname<input type="text" name="lastname">
</form>
Using this code I could save the uploaded file to the directory but the other form can't be save. There isn't really an error message when I upload the file but its asking for the other fields to be filled even though it is populated in the separate form.
What I want is to save the uploaded picture to the directory without affecting the other form, vice versa.
Thanks in advance to those who can suggest a solution.

Related

How to get a full path of file uploaded via HTML form in django view.py file?

home.html
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name = 'img' >
<button type="submit"> Post On Facebook </button>
</form>
views.py
def home(request):
if request.method == 'POST':
# get the image absolute location
return render(request,'home.html')
I want the file path, so that I can upload the file on facebook using GraphAPI.
You need to set your upload path in your models file.
Then you can save it to that particular path in your view function.
For details refer - https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html

Redirecting buttons with values to other django templates/views

Firstly, I am getting a csv file from the user.
(Template file:)
<form method="post" action="{% url 'rowcol' %}" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="file" accept=".csv">
<button type="submit">Upload File</button>
</form>
Then i am generating a list of all the columns present in the file and then calling another html file. (views.py:)
def rowcol(request):
if request.method == 'POST':
file = request.FILES['file']
dataset=pd.read_csv(file)
lst=list(dataset)
return render(request, 'Link5_rc.html', {'arr':lst})
return HttpResponse('')
In that html file, i am creating buttons for all the columns present.(Link5_rc.html:)
{% for link in arr %}
<form action=" " method="post">
<button name="{{link}}" type="submit" value="{{link}}">{{link}}</button>
</form>
{% endfor %}
Now the following is the part where i am stuck: I want these buttons to redirect to another html page or maybe a view in views.py , where i can show to the user which column he/she selected and then perform further actions on that particular column.
You can pass one or more values to the request as in the following example:
Some text
You can use variables like:
Some text
In your app urls.py you should set the following to receive the extra data in the request:
url(r'^your_name/(?P<value_1>[\d\D]+)$', views.your_view, name="your_url_alias")
Then, in your view function you should receive the data as in:
def your_view(request, value_1):
An then you can use the value to filter the queryset.

Django: can we alter filefield such that when a file is selected, it immediately gets uploaded

I was just wondering: Will it be possible to alter the File Field such that when a file is selected, it immediately gets uploaded, without the means of additional button?
Assuming that I imported everything from .models, .forms, urls.py, etc successfully,
Codes in models.py:
class data(models.Model):
Datas = models.FileField(upload_to='datas/upload')
Codes in forms.py:
class form1(forms.ModelForm):
class Meta:
model = data
fields = ('Datas',)
Codes in views.py:
def upload(request):
if request.method == 'POST' and 'btnform1' in request.POST:
newform1 = form1(request.POST, request.FILES)
if newform1.is_valid():
newform1.save()
return redirect('list')
Codes in upload.html:
<h2>Data</h2>
<form method="post" enctype="multipart/form-data"> {% csrf_token %}
{{newform1.as_p}}
<!-- <button type="submit" class="btn btn-primary" name="btnform1">Upload Data</button>-->
</form>
Can anyone guide me and possibly give a solution on how to do it if it is even possible? Thank you.
For this you don't to change anything on backend but a javascript snippet to trigger form submit on change event of file field button.
Assuming your input file field has id ="id_file" and form id="image-upload-form".
If your html looks like.
<form id="image-upload-form" method="POST" role="form" enctype="multipart/form-data">
{% csrf_token %}
<input name="id_Datas" type="file" id="id_datas">
<button type="submit" class="btn btn-primary" name="btnform1">Upload</button>
</form>
then js would look like.
$("#id_datas").on("change", function(event){
$("#image-upload-form").submit();
});
Explaination:
See when you have a form in your html, a form role is to collect the data of input elements in it, and wrap this data and take the necessary method defined in form i.e. "GET", "POST" etc on the action defined which is a url like "/upload_file"
Now by default the form will only do this when the user clicks on button element with type submit contained within the form. Since you don't want this behaviour where user will have to click, you can also do via javascript, if you the html defined as above, then in order to test the behaviour you can select the file in the file upload option and go to developer console and run
this
$("#image-upload-form").submit();
You will see the same behaviour happens when you click on the button as well. So we are doing this on change event to automatically submit the form when user selects a file.
Hope this helps, if not then let me know which part.

how to delete an object in django [duplicate]

i want to delete a task from the database so i use this code
this is my delete view
def task_Delete(request,id=None):
if request.method == 'POST':
form = TaskForm()
id = int(request.POST.get('task.id'))
task = Task.objects.get(id=id)
task.delete()
messages.success(request,"successfully delete")
return render_to_response('home.html', {'form': form})
and that is my urls.py
url(r'^task_Delete/$', views.task_Delete, name='task_Delete')
this the code of the button delete :
<form action="{% url 'task_Delete' %}" method="post" >
{% csrf_token %}
<input type="hidden" name="task_id" value="{{task.id}}" />
<input type="submit" value="delete task">
</form></td>
</tr>
when i click on delete nothing happend i don't know why , please help thanks in advance
There are various problems in your code (for example the TaskForm is not needed at all) however if you change the line
id = int(request.POST.get('task.id'))
to
id = int(request.POST.get('task_id'))
the object will probably be deleted; remember that the request parameter's name will be the same as the name of the input (task_id). I recommend using proper CBVs (a DeleteView) for what you want to do - if you want a slow and comprehensive tutorial on that I recommend this article: https://spapas.github.io/2018/03/19/comprehensive-django-cbv-guide/

What am I not doing right in this django file upload form?

This is my form:
from django import forms
class UploadFileForm(forms.Form):
titl = forms.CharField(max_length=50)
ffile = forms.FileField()
This is my views.py file:
def handle_uploaded_file(file_path):
print "handle_uploaded_file"
dest = open(file_path.name,"wb")
for chunk in file_path.chunks():
dest.write(chunk)
dest.close()
def handle_upload(request):
c = {}
c.update(csrf(request))
if request.method == "POST":
form = UploadFileForm(request.POST)
if form.is_valid():
handle_uploaded_file(request.FILES["ffile"])
return HttpResponseRedirect("/thanks")
else:
form = UploadFileForm()
c.update({"form":form})
return render_to_response("upload.html",c)
And this is the content of upload.html:
<form enctype="multipart/form-data" method="post" action="/handle_upload/">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Upload it"/>
</form>
Whenever I try to submit the form, I get a "This field is required" for the ffile field. What am I doing wrong? Just to mention, I am uploading a file each time.
Just for future reference. I had the same error, though I included request.FILES in form initialization. The problem was in the template: I forgot to add enctype="multipart/form-data" attribute to the <form> tag.
form = UploadFileForm(request.POST, request.FILES)
If you have included request.FILES and added the enctype="multipart/form-data", but are still seeing this error, it could be you are not declaring the <input> correctly.
For example, if explicitly declare the input html in your template like:
<input type="file" value="Upload CSV File" />
You may not be passing the expected input id or name attributes of the input form element.
Be sure that your template is using the form element tag, i.e. {{ form.file }},
which django will then render as: <input id="id_file" name="file" type="file" required=""> on the page.

Categories