So I am trying to upload and save a csv file to a variable via a POST to a url. I have looked through the django documentation on file uploads found here. I just don't understand the use of a form? What's the purpose in this situation?
They use an example with a form:
from django import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
Upload html:
<form enctype="multipart/form-data" action="/upload/" name="test" method="post">
<input id="file" type="file" name="test" />
<input id="signUpSubmit" type="submit" value="Submit">
</form>
models.py
from django.db import models
class Upload(models.Model):
name = models.CharField(max_length=100)
file = models.FileField(upload_to="images")
forms.py
from django import forms
from app_name.models import Upload
class UploadForm(forms.ModelForm):
class Meta:
model = Upload
views.py
def upload_file(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
upload.html
<form enctype="multipart/form-data" action="/upload/" name="test" method="post">
{% csrf_token %}
{{form.as_p}}
<input id="signUpSubmit" type="submit" value="Submit">
</form>
Related
I also created UserUpdateForm class which i did not include here and if i try to change my name and email through UserUpdateForm class it works but if try for profile picture it did not works
views.py
from django.shortcuts import render, redirect
from .forms import ProfileUpdateForm
def editprofile(request):
if request.method == 'POST':
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
if u_form.is_valid():
p_form.save()
return redirect('profile')
else:
p_form = UserRegisterForm(instance=request.user.profile)
context = {
'p_form': p_form,
}
return render(request, 'users/editprofile.html', context)
forms.py
from django import forms
from .models import Profile
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
html template
<form class="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form__group form__avatar">
<label for="avatar">Upload Avatar</label>
<input class="form__hide" required type="file" name="avatar" id="avatar" accept="image/png, image/gif, image/jpeg, image/jpg"/>
</div>
</form>
I am trying to send data from django forms to backend sqlite3. But I am unable to do so. I am not also getting any error or warning that help me to sort it out.
Here is models.py file
from django.db import models
GENDER_CHOICES = [
('Male', 'M'),
('Female', 'F')]
class upload(models.Model):
name = models.CharField(max_length=100)
gender = models.CharField(max_length=10, choices=GENDER_CHOICES)
phone = models.CharField(max_length=50,null=True)
email= models.EmailField(max_length=50,null=True)
file=models.FileField(upload_to='uploads/')
def __str__(self):
return self.name
here is forms.py file
from django.forms import ModelForm
from .models import upload
class uploadForm(ModelForm):
class Meta:
model = upload
fields = ['name', 'gender', 'phone', 'email','file']
Here is view.py file
from django.shortcuts import render
from .forms import uploadForm
from django.shortcuts import render
def home(request):
if request.method == 'POST':
form = uploadForm()
if form.is_valid():
form=form.save()
return HttpResponseRedirect('/')
else:
form = uploadForm()
return render(request,'home.html',{'print':form})
I am unable to understand where is the issue
This is how template file look like
<form method="post">
{% csrf_token %}
{{ print.as_p }}
<input type="submit" value="Submit">
</form>
EDIT
This issue is with FileField, I removed it, and it start saving in django database. What I want is to save file in media folder and other data in database
I also added enctype="multipart/form-data" in form
I don't think your actually sending anything to the database.
Where is says form = uploadForm() you need state you want the posted data to be sent. so this needs to be form = uploadForm(request.POST) it should then work I believe. Also when saving the form, remove the form=form.save() and leave it as form.save()
Try it out and let us know?
Solution to my post
For handling files, I need to add encryption type to my form as
enctype="multipart/form-data"
Once I added that, to access the files I should use request.FILES along with request.POST
So now I have this home function in views.py file
def home(request):
if request.method == 'POST':
form = uploadForm(request.POST,request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
form = uploadForm()
return render(request,'home.html',{'print':form})
and my template form looks like
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ print.as_p }}
<input type="submit" value="Submit">
</form>
Credit : https://youtu.be/Rr1-UTFCuH4?t=244
Only the button is visible and headings are visible cannot see CharField
forms.py
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from compare.forms import NameForm
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
index.htm
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
You should give the if form.is_valid() part, one more tab.
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from compare.forms import NameForm
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
I'm not yet allowed to add comments to your question, but you did notice, that your view renders name.html while you're providing the code for index.htm.
Basically your code seems valid, while it can be further optimized:
def get_name(request):
form = NameForm(request.POST or None)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
return render(request, 'name.html', {'form': form})
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
This should work by adding editing {{form.as_p}}
I want to write form and when submit it write "welcome!" in my page.But after I submit form method still is GET!!what's wrong?
this is my models:
from django.db import models
import django_tables2 as tables
from django import forms
class Form1(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
this is my view:
def contact(request):
if request.method == 'POST': # If the form has been submitted...
# ContactForm was defined in the previous section
form = Form1(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
return render(request, 'student/Home.html',{'message':'welcome'})
else:
form = Form1() # An unbound form
return render(request, 'student/Home.html', {'form': form})
this is my template(Home.html):
<!DOCTYPE html>
<html>
<body>
<form action="{% url 'student:contact' %}" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Submit" />
</form>
<p>{{message}}<p>
</body>
</html>
I'm trying to upload csv through django but it's not working..
Code
Views.py
from django.shortcuts import render_to_response
from forms import UploadForm
from django.http import HttpResponseRedirect
def create(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/success/url/')
else:
form = UploadForm()
return render_to_response('upload.html', {'form': form})
Url.py
urlpatterns = patterns('',
(r'^$', create),
#url(r'^articles/create/$', create, name='done'),
url(r'^articles/create/$', 'article.views.create'),
)
models.py
from django.db import models
from time import time
def get_upload_file_name(instance, filename):
return "uploaded_files/%s_%s" % (str(time()).replace('.','_'), filename)
class Article(models.Model):
file = models.FileField(upload_to=get_upload_file_name)
Forms.py
from django import forms
from models import Article
class UploadForm(forms.ModelForm):
class Meta:
model = Article
html file
{% csrf_token %}
{{form.as_p}}
Your template needs to be:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" />
</form>
See the binding uploaded files to a form section in the documentation.