Django: upload image can't find uploaded image - django

I have already tried searching stackoverflow, but couldn't find anything. My problem is that I cannot seem to find the folder where the pictures I upload is supposed to be. Seems like everything else works?
Here you can see my code:
Settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Views.py
#login_required(login_url="/login/")
def model_form_upload(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES,instance=request.user)
if form.is_valid():
form.save()
print("Form is valid")
return redirect('/questions/profile')
else:
form = DocumentForm(instance=request.user)
return render(request, 'questions/model_form_upload.html', {
'form': form
})
Urls.py
url(r'^upload/$', views.model_form_upload, name='upload')
Models.py
import os
def get_image_path(instance, filename):
return os.path.join('users/', str(instance.id), filename)
class Document(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
profile_image = models.FileField(upload_to=get_image_path,
blank=True, null=True)
Forms.py
from questions.models import Document
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ('profile_image',)
model_form_upload.html
{% extends 'questions/base.html' %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
<p>Return to profile</p>
{% endblock %}

Related

Getting the uploaded images in Django

I have a class with multiple images that can be uploaded. I am trying to use Bootstrap Carousel for a slide show of the images, but I am having a hard time getting it.
Models.py
class Content(models.Model):
title = models.CharField(max_length=250)
content = models.TextField(max_length=1000)
website = models.URLField()
github = models.URLField()
def __str__(self):
return self.title
def get_image_filename(instance, filename):
title = instance.post.title
slug = slugify(title)
return "post_images/%s-%s" % (slug, filename)
class Images(models.Model):
post = models.ForeignKey(Content, on_delete=models.CASCADE)
image = models.ImageField(upload_to=get_image_filename,
verbose_name='Image')
Views.py
def home(request):
content = Content.objects.all()
name = request.POST.get('name')
email = request.POST.get('email')
message = request.POST.get('message')
if request.method == "POST":
if not name and not email and not message:
content = 'name: ' + name + '\n' + 'email: ' + email + '\n' + '\n' + message
send_mail('Email from Portfolio', content, 'email', ['email'], fail_silently=False)
messages.success(request, "Your Email has been sent")
return redirect('home')
else:
return render(request, 'appOne/home.html', {'content':content})
#login_required
def post(request):
ImageFormSet = modelformset_factory(Images,
form=ImageForm, extra=3)
#'extra' means the number of photos that you can upload ^
if request.method == 'POST':
postForm = PostForm(request.POST)
formset = ImageFormSet(request.POST, request.FILES,
queryset=Images.objects.none())
if postForm.is_valid() and formset.is_valid():
post_form = postForm.save(commit=False)
post_form.user = request.user
post_form.save()
for form in formset.cleaned_data:
#this helps to not crash if the user
#do not upload all the photos
if form:
image = form['image']
photo = Images(post=post_form, image=image)
photo.save()
# use django messages framework
messages.success(request,
"Yeeew, check it out on the home page!")
return HttpResponseRedirect("/")
else:
print(postForm.errors, formset.errors)
else:
postForm = PostForm()
formset = ImageFormSet(queryset=Images.objects.none())
return render(request, 'appOne/post.html',
{'postForm': postForm, 'formset': formset})
template:
{% extends 'appOne/base.html' %}
{% load static %}
{%block content%}
{% for obj in content.images_set.all %}
<img src="{{ obj.images.url}}" alt="">
{% endfor %}
{% endblock %}
</html>
Using the template above, when I tried to go home, it does not show anything.
I am in the process of showing the images. The carousel bootstrap is not yet coded on the template.
you are using wrong modelField name. replace {{ obj.images.url}} to {{ obj.image.url}}
example:
{% extends 'appOne/base.html' %}
{% load static %}
{%block content%}
{% for obj in content.images_set.all %}
<img src="{{ obj.image.url}}" alt="">
{% endfor %}
{% endblock %}
</html>

Django Image Upload working but not General File

I am facing a situation where I am able to upload Images, but not general files. I am using javascript to track the progress, which says file upload is successful, but file is not there in the media folder. When I do that for images, it works.
Basically, image upload was working, and I tried to copy the same thing and do it for general file upload. Here is the code below.
Models
class Upload(models.Model): # image upload model
image = models.ImageField(upload_to='images')
def __str__(self):
return str(self.pk)
class FileUpload(models.Model): # file upload model
video = models.FileField(upload_to='fileuploads/')
def __str__(self):
return str(self.pk)
Forms:
class UploadForm(forms.ModelForm):
class Meta:
model = Upload
fields = ('image',)
class FileUploadForm(forms.ModelForm):
class Meta:
model = FileUpload
fields = ('video',)
Views:
def home_view(request):
form = UploadForm(request.POST or None, request.FILES or None)
if request.is_ajax():
if form.is_valid():
form.save()
return JsonResponse({'message': 'hell yeah'})
context = {
'form': form,
}
return render(request, 'uploads/main.html', context)
def file_view(request):
form = FileUploadForm(request.POST or None, request.FILES or None)
if request.is_ajax():
if form.is_valid():
form.save()
return JsonResponse({'message': 'hell yeah'})
context = {
'form': form,
}
return render(request, 'uploads/main1.html', context)
The HTML template for Image Upload
{% extends "uploads/base.html" %}
{% block content %}
<div id="alert-box"></div>
<div id="image-box"></div>
<br>
<form action="" id="upload-form">
{% csrf_token %}
{{form.as_p}}
</form>
<br>
<div id="progress-box" class="not-visible">progress</div>
<div id="cancel-box" class="not-visible">
<button id="cancel-btn" class="btn btn-danger">cancel</button>
</div>
{% endblock content %}
The only difference with html template for File upload is
{% extends "uploads/base1.html" %}
Which I use a different base html template.
Settings:
STATIC_URL = '/static/'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = "/media/"
I am using the code from here - https://github.com/hellopyplane/Progress-bar
The javascript code uses a hardcoded field "image", which is called "video" in your second form.

How to upload and display videos on django

I have been trying to add a view that uploades videos and displays them in the main template, well while adding code, I realized that the view that uploades the file isn't being rendered while the view that shows the uploded file in the template gets rendered but it doesnt show anything because nothing is being uploded. I dont know where the error might be but I think it is on the views.py, maybe the urls.py.
views.py
def upload(request):
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
return redirect('home')
print('succesfully uploded')
else:
form = PostForm()
print('didnt upload')
return render(request, 'home.html', {'form': form})
def home(request):
contents = Post.objects.all()
context = {
"contents": contents,
}
print("nice")
return render(request, 'home.html', context)
urls.py
urlpatterns = [
path('', views.home, name='home'),
path('upload', views.upload, name='upload'),
]
models.py
class Post(models.Model):
text = models.CharField(max_length=200)
video = models.FileField(upload_to='clips', null=True, blank="True")
user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username')
def __str__(self):
return str(self.text)
forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('text', 'video')
exclude = ['user']
home.html (uplodes the content and displays it)
<div class="user-content">
{% for content in contents %}
<li class="">{{ content.text }}
{% if content.video %}
<video class="video" width='400'>
<source src='{{ content.video.url }}' type='video/mp4'>
</video>
{% endif %}
</li>
{% endfor %}
</div>
<div class="uplodes">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="text" placeholder="Add a comment..." required="" id="id_text">
<input type="file" name="video" id="id_video">
<button class="submit-button" type="submit">Save</button>
</form>
</div>

Django image:this field is required

I am trying to send a form with an image, I select the image but I always get: "this field is required" when I send the form.
here is my code:
models.py:
from django.db import models
from django.contrib.auth.models import User
class Picture(models.Model):
created_at = models.DateField(auto_now_add=True)
update_at = models.DateField(auto_now=True)
image = models.ImageField()
caption = models.CharField(max_length=50)
author = models.ForeignKey('auth.user', on_delete=models.CASCADE, related_name='pictures')
forms.py:
from django import forms
class PictureForm(forms.Form):
image = forms.ImageField()
caption = forms.CharField(max_length=50)
views.py:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import Picture
from .forms import PictureForm
from django.contrib.auth.models import User
def pictures_view(request):
pictures = Picture.objects.all()
context = {'pictures': pictures}
return render(request, 'pictures/pictures.html', context)
def picture_form_view(request):
if request.method == 'POST':
form = PictureForm(request.POST, request.FILES)
if form.is_valid():
clean_data = form.cleaned_data()
Picture.objects.create(clean_data)
return HttpResponseRedirect('/')
else:
form = PictureForm()
return render(request, 'pictures/picture_form.html', {'form': form})
HTML:
{% extends 'pictures/base.html' %}
{% block title %}publish{% endblock %}
{% block content %}
<form class="form" action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
{% endblock %}
And a Little question, how can I complete the field author automaticly with the actual user?
first of all ImageField in model takes one compulsory argument upload_to so in your models
class Picture(models.Model):
###
image = models.ImageField(upload_to='upload/to/path')
###
now in your view
def picture_form_view(request):
if request.method == 'POST':
form = PictureForm(request.POST, request.FILES)
if form.is_valid():
clean_data = form.cleaned_data()
Picture.objects.create(**clean_data)
return HttpResponseRedirect('/')
else:
form = PictureForm()
return render(request, 'pictures/picture_form.html', {'form': form})
and to save current logged in user as default override form_valid()
method in Form class like
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
Try to set enctype to "multipart/form-data" in the form tag.
<form action="#" method="post" enctype="multipart/form-data">
input here ...
</form>

Error on uploading image in django: "coercing to Unicode: need string or buffer, tuple found"

Trying to work with ImageField in django.
Here are my models
class Album(models.Model):
title = models.CharField(max_length=100)
def __unicode__(self):
return self.title
class Photo(models.Model):
image = models.ImageField(upload_to='photos/')
album = models.ForeignKey(Album)
title = models.CharField(max_length=100, default="")
def __unicode__(self):
return self.title
class PhotoModelForm(forms.ModelForm):
class Meta:
model = Photo
Here is a part of urls.py
...
url(r'^trial/upload/$', 'trial.views.upload'),
...
views.py
def upload(request):
if request.method == 'POST':
form = PhotoModelForm(request.POST, request.FILES)
if form.is_valid():
photo = form.save()
return render_to_response('trial/thanks_upload.html',{
'photo': photo
}, context_instance = RequestContext(request))
else:
form = PhotoModelForm()
return render_to_response('trial/upload.html', {
'form': form
}, context_instance = RequestContext(request))
upload.html
<form enctype="multipart/form-data" action="/trial/upload/" method="post">
{% csrf_token %}
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }}: {{ field }}
</div>
{% endfor %}
<p><input type="submit" value="Upload" /></p>
</form>
But on saving I have next error:
TypeError at /trial/upload/
coercing to Unicode: need string or buffer, tuple found
Errors appears on photo.save
Does anybody has ideas why could it be? Why tuple appears at all? I'm sure there is a stupid bug...
I've got it myself. In settings.py there is MEDIA_ROOT setting, which was
MEDIA_ROOT = 'd:/dev/python/scripts/app/media/',
Python makes the object tuple because of the comma at the end. That's why it couldn't save the object. Watch your commas next time!