I am using Djnago.i Have html Form such as below,
<form method="POST" action="{% url 'someaction' %}" enctype="multipart/form-data">
<input type="file" name="image" id="image">
</form>
How to check request.FILES['image'] is Selected or not in djnago view file?
Do:
image = request.FILES.get('image')
if image is None:
# request.FILES['image'] is not posted
Related
How would I best loop a form like this (there is other code in the form but this is an example for image uploading)
<form action="{% url "upload" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="image_file">
<input type="file" name="image_file2">
<input type="file" name="image_file3">
<input type="file" name="image_file4">
<input type="file" name="image_file5">
<input type="submit" value="submit" />
</form>
for single file uploading but need it multifile uploading:
def image_upload(request):
if request.method == "POST" and request.FILES["image_file"]:
image_file = request.FILES["image_file"]
fs = FileSystemStorage()
filename = fs.save(image_file.name, image_file)
image_url = fs.url(filename)
print(image_url)
return render(request, "upload.html", {
"image_url": image_url
})
return render(request, "upload.html")
Just not sure how to loop it so images are stored along with filename in a var for the db (at a later point) also just a thought, might not always be uploading all five files could be three or none
Guys I'm new to django I tried uploading images in the imagefield but it's not creating media folder and the database image column is also blank.
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
models.py
class Profile(models.Model):
name = models.CharField(max_length=50)
image = models.ImageField(upload_to='images/')
image.html
<form method="POST" enctype="multipart/form-data>
{% csrf_token %}
<input type="file" class="form-control" id="customFile" name="image"/></div>
<input type="text" class="form-control" name="name" placeholder="">
</div>
</form>
views.py
def hotel:
if request.method == "POST" :
post=Profile()
post.image= request.POST.get('image')
post.name = request.POST.get('name')
post.save()
return redirect('/vendor_dashboard/profile_pic')
return render(request,'profile.html')
Even tried manually creating the media file Django.
Still nothing!!
Any help Will be appreciated
Uploaded files are in request.FILES instead of request.POST. So your file handling should look like this:
# post.image= request.POST.get('image')
post.image = request.FILES['image']
I'd recommend to read the Django docs about file uploads
use request.FILES:
def hotel:
if request.method == "POST" :
post=Profile()
post.image= request.FILES['image']
post.name = request.POST.get('name')
post.save()
return redirect('/vendor_dashboard/profile_pic')
return render(request,'profile.html')
You have to include {{form.media}} to the django form template if you want to post any type of media to django
<form method="POST" enctype="multipart/form-
data>
{% csrf_token %}
{{form.media}}
<input type="file" class="form-control"
idd="customFile" name="image"/></div>
<input type="text" class="form-control"
name="name" placeholder="">
</div>
</form>
edit:
and in views.py you have to use request.FILES to get any media file(forgot to mention this)
request.FILES.get('image')
and to get the image from media use .url
{% Profileobject.image.url %}
Code in template:
<form action="/html/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" id="html_file" name="html_file" />
<input type="submit" value="Upload" />
</form>
and in view
def add_html(request):
if request.POST:
#do something with html
return redirect('/')
else:
return render_to_response('add_html.html')
I need to html-file is loaded and read its contents, not upload to the server.
But I get an error:
csrf token missing or incorrect
How fix?
My guess is that the {% csrf_token %} is empty when your template is rendered.
Per the CSRF documentation you should use the render function instead of the render_to_response function to ensure the RequestContext, which includes the csrf_token, is properly loaded into your template.
You can achieve what you want with the following code:
forms.py:
from django import forms
class ReadFileForm(forms.Form):
file = forms.FileField()
views.py:
from .forms import ReadFileForm
def read_file(request):
form = ReadFileForm()
if request.method == 'POST':
form = ReadFileForm(request.POST, request.FILES)
if form.is_valid():
content = request.FILES['file'].read()
# Do something with content
return render(request, 'read_file.html', locals())
templates/read_file.html:
<html>
<head></head>
<body>
<h3>Read File Content</h3>
<form enctype="multipart/form-data" action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Save">
</form>
</body>
</html>
I've been trying to figure out how to create a custom html template that when submitted will upload to a model form. I'm newer to Django so so far i've been a little confused on the Django Docs on the forms. I have created a custom HTML Template it looks like:
HTML:
<form role="form" method="post" action="." id="js-upload-form" enctype="multipart/form-data">
{% csrf_token %}
<img id="image1" src="/media/{{ gallery.logo }}" alt="">
<input type="file" name="logo" id="logo" multiple>
<br>
<input type="submit" value="Register" id="js-upload-submit" >
</form>
You can notice that I have given the input ID = logo. When I click submit I would like this to upload an image to my ModelForm.
Form:
class UploadFileForm(ModelForm):
logo = forms.ImageField(required=False)
class Meta:
model = Content
fields = ['logo']
Models:
class Content(models.Model):
logo = models.ImageField(upload_to=content_file_name, null=True, blank=True)
Is there anyway with the specific way I have designed my HTML template to submit the image to the Model Form? I am trying to avoid using { form.as_p } and such as it doesnt do the customization I would like.
You should send the form object to the template and call the {{form.logo}} field.
View:
if request.method == 'POST': # When the form is submitted
form = UploadFileForm(request.POST)
if form.is_valid():
new_content = form.save()
# After the form.save a new model is created
# and the file is uploaded to the desired location
else:
form = UploadFileForm()
ctx = {}
ctx['form'] = form
return render_to_response('yourtemplate.html', ctx, context_instance=RequestContext(request))
Template:
<form role="form" method="post" action="." id="js-upload-form" enctype="multipart/form-data">
{% csrf_token %}
{{form.logo}}
</form>
Customization:
If you would like to customize the input field, you should hide the form field like:
<form role="form" method="post" action="." id="js-upload-form" enctype="multipart/form-data">
{% csrf_token %}
{{form.logo.as_hidden}} # This won't show the input
</form>
And now to customize the input you should show your custom input and via jQuery or JavaScript bind the custom input/button to the hidden form logo field.
E.g:
If you want to trigger the file select with a custom button, you should do:
# ... Other code
<button class='btn btn-success yourclass' onClick='selectFile'>
<script>
function selectFile(){
$('#id_logo').click()
}
<script>
Using Django 1.6 with Python 2.7.
My model has a BooleanField variable, and I want the user to be able to change this via POST by clicking a button to change it from False to True, or vice versa. Having issues rendering the template.
Model currently:
class Pic(models.Model):
Name = models.CharField(max_length=100)
Good = models.BooleanField()
Image = models.FileField(upload_to="images/")
def __unicode__(self):
return self.Name
App urls is:
url(r'^(?P<Pic_id>\d+)/$', views.single_picture, name='single_picture'),
In the template I have:
<form action="{% url 'single_picture' Pic.Good %}" method="post">
{% csrf_token %}
{% if Pic.Good %}
<input type="checkbox" name="choice" id="{{ Pic.Good }}" value="False" />
<label for="{{ Pic.Good }}">False</label><br />
{% else %}
<input type="checkbox" name="choice" id="{{ Pic.Good }}" value="True" />
<label for="{{ Pic.Good }}">True</label><br />
{% endif %}
<input type="submit" value="good" />
</form>
And for my view I have:
def single_picture(request, Pic_id):
if request.method == 'GET':
pic = get_object_or_404(Pic, pk=Pic_id)
latest_pictures_list = Pic.objects.all()
return render(request, 'pictures/single_picture.html', {'Pic': pic, 'latest_pictures_list': latest_pictures_list})
elif request.method == 'POST':
pic = get_object_or_404(Pic, pk=Pic_id)
latest_pictures_list = Pic.objects.all()
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Pic.DoesNotExist):
return render(request, 'pictures/single_picture.html', {'Pic': pic, 'error_message': 'uhhhh...',
})
else:
selected_choice.save()
return HttpResponseRedirect(reverse('pictures/single_picture.html', {'Pic': pic}))
I'm not sure if there are multiple errors at this point or not. Currently when trying to view the template, I get
Reverse for 'single_picture' with arguments '(True,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []
for the '< form >' line. I'm guessing it's to do with my View?
I think the issue is in your template, in the line
<form action="{% url 'single_picture' Pic.Good %}" method="post">
Your regex in urls.py is r'^(?P<Pic_id>\d+)/$', I'm guessing that it's expecting the id of the Picobject you return in the GET request and not a boolean, in which case the line should be
<form action="{% url 'single_picture' Pic.id %}" method="post">
Likewise, in the lines underneath, there isid="{{ Pic.Good }}" which will display as HTML as id=True or id=False, which I suppose you don't want. You need to replace that bit by id="{{Pic.id}}"