Django, viewing uploaded files and videos - python

I would like to be able to view my uploaded files. I really have a poor grasp of what I am doing.
views.py
def upload_file(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('learning_logs:topics'))
else:
form = DocumentForm()
return render(request, 'learning_logs/model_form_upload.html', {'form':form})
def file_preview(request):
videos = Document.objects.all()
context = {'videos':videos}
return render(request, 'learning_logs/video.html', context)
models.py
class Document(models.Model):
docfile = models.FileField(upload_to = 'documents/')
upload_at = models.DateTimeField(auto_now_add = True)
forms.py
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ['docfile']
I have uploaded videos and pictures.
As the files are passed onto the HTML, I can only see the names of the files I uploaded. I can't click on the links and view the files.
I would like to have an actual video player to play the videos, or view the pictures.

Use url attribute of FileField in your template and pass that URL to your favorite player js library.

Related

Django models file field regex?

I want to be able to check if the files that are going to be uploaded through forms contain any sensitive information. Can someone please give me an idea on how I can accomplish this.
This is my code.
Models.py
class File(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
doc = models.FileField(upload_to='files/docs/', validators=[FileExtensionValidator(allowed_extensions=['pdf','docx'])])
def __str__(self):
return self.title
My upload code in views.py
def upload_file(request):
if request.method == 'POST':
form = FileForm(request.POST, request.FILES) #request.Files handles file uploads
if form.is_valid():
form.save()
file_dlp()
return redirect('file_list')
else:
form = FileForm()
return render(request, 'upload_file.html', {
'form':form
})

Poll is not saving

I am building a PollApp and I am stuck on a Problem..
I build a poll add feature for add images in the poll . BUT images are not adding in the Poll.
When i select images in field then save it redirect to the same page and saying "This field is required".
models.py
class ImageChoice(models.Model):
image_poll = models.ForeignKey(ImagePoll, on_delete=models.CASCADE)
choice_image = models.FileField()
views.py
def polls_add(request):
if request.method == 'POST':
form = ImagePollAddForm(request.POST)
if form.is_valid():
poll = form.save(commit=False)
poll.owner = request.user
poll.save()
new_choice1 = ImageChoice(poll=poll, image=form.cleaned_data['choice1']).save()
context = {
'form': form,
}
return render(request, 'add_poll.html', context)
forms.py
class ImagePollAddForm(forms.ModelForm):
choice1 = forms.FileField()
class Meta:
model = ImagePoll
fields = ['choice1']
When i try to upload images in each field then click to save then it is not uploading.
I also tried by adding request.FILES in form = ImagePollAddForm(request.POST) BUT it is showing ImageChoice() got an unexpected keyword argument 'poll' .
You use invalid field name, your model has image_poll field but not poll. And your model does not have image field but choice_image
ImageChoice(image_poll=poll, choice_image=form.cleaned_data['choice1']).save()

Upload Image in the wrong directory in django ImageField

When I upload a photo, the photo is loaded successfully, but the photo is placed in the wrong directory.
Instead of placing the image on the path to 'media/posts-pics/' - as I have outlined in my Post model - it is placed on the 'media' path.
These are my files:
models.py
class Post(models.Model):
index_pic = models.ImageField(upload_to='posts-pics/')
Project.urls.py
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
def add_post(request):
if request.method == "POST":
form = AddPostForm(request.POST, request.FILES)
if form.is_valid():
new_post = form.save(commit=False)
new_post.index_pic = form.cleaned_data['index_pic']
new_post.save()
return redirect('view_post')
else:
form = AddPostForm()
template = 'post/add_edit_post.html'
context = {'form': form}
return render(request, template, context)
def edit_post(request, slug):
post = get_object_or_404(Post, slug=slug)
if request.method == "POST":
form = AddPostForm(request.POST, request.FILES, instance=post)
if form.is_valid():
Post.objects.filter(id=post.id).update(title=request.POST['title'],
index_pic=form.cleaned_data['index_pic'],
)
return redirect('view_post')
else:
form = AddPostForm(instance=post)
template = 'post/add_edit_post.html'
context = {'form': form}
return render(request, template, context)
I used exactly the same code for add_post, and the photo was in its place, but I got into trouble in edit_post. what's wrong ?
Notice:
Technically I can delete 'media/post-pics' but this is done with a
special purpose and the purpose is: Each app have its folder for
saving images.
The problem is that you're no using your ModelForm the right way.
In the edit_post view, you want to replace this:
Post.objects.filter(id=post.id).update(
title=request.POST['title'],
index_pic=form.cleaned_data['index_pic'],
)
with a plain simple:
form.save()
which will take care of the updating the post passed as form.instance (using sanitized data, which is not the case with your current code)
FWIW, in your add_post view, you also want to replace this
new_post = form.save(commit=False)
new_post.index_pic = form.cleaned_data['index_pic']
new_post.save()
with a plain simple:
new_post = form.save()
Once again, the whole point of ModelForms is that they know how to create and update model instances.

Django user specific folders

I want to create user specific folders for files uploaded by users. This is my views.py:
#login_required
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('upload.views.list'))
else:
form = DocumentForm() # An empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render_to_response(
'upload/list.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
This is my models.py:
class Document(models.Model):
docfile = models.FileField(upload_to='uploads/%Y.%m.%d')
My idea is this. Instead of naming it uploads/%Y.%m.%d I stick the username somewhere in there. Is there a way to do that?
I do something like that in my models.py:
def _upload_path(instance,filename):
return instance.get_upload_path(filename)
class Document(models.Model):
docfile = models.FileField(upload_to=_upload_path)
user = models.ForeignKey('auth.User')
def get_upload_path(self,filename):
return "static/uploads/"+str(self.user.id)+"/"+filename

Django ImageField: files dont get uploaded

I implemented some ImageFields in my model and installed PIL (not the cleanest install). Things seem to work as I get an upload button in the admin and when I call the .url property in the view I get the string with the filename + its upload property.
The problem is that the file is not there, apparently it doesnt get uploaded once I save the model.
Any idea?
Thanks
Here's a sample of my code situation
models.py
class My_Model(models.Model):
[...]
image = models.ImageField(upload_to = 'images/my_models/main')
view.py
'image': query.my_model.image.url
result:
static/images/my_models/main/theimage.png
Make sure that you're binding request.FILES to the form when POSTing, and that the form is declared as multi-part in the template
Here's the view from one of my applications:
#login_required
def submit(request):
if request.method == 'POST':
(Photo.objects.count()+1, request.FILES['photo'].name.split(".")[1]), request.FILES['photo'])}
form = PhotoForm(request.POST, request.FILES)
if form.is_valid():
new = Photo(photo=request.FILES['photo'], name=request.POST['name'])
new.save()
return HttpResponseRedirect('/') # Redirect after POST
else:
form = PhotoForm()
return render_to_response('app/submit.html', {'form': form}, context_instance=RequestContext(request))
and the PhotoForm class:
class PhotoForm(forms.ModelForm):
class Meta:
model = Photo
fields = ('name', 'photo')

Categories