Django models file field regex? - python

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
})

Related

Django - how to make a CloudinaryField not mandatory and how to allow user to delete their uploaded image?

Hej, I am just beginning to learn Django and I want my users to be able to upload a profile picture, so I extended the User model with a Profile model, however, so far I have not figured out how to make the image upload non-mandatory. And when the user has added a picture, I would like them to be able to remove it as well.
Screenshot - Not able to Submit without adding file
Screenshot - Not able to remove the added file
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField()
profile_image = CloudinaryField('profile_image')
def __str__(self):
return self.user.username
forms.py
class ProfileForm(ModelForm):
class Meta:
model = Profile
fields = ('bio', 'profile_image',)
views.py
#login_required(login_url='login')
def createPost(request):
form = PostForm()
if request.method == "POST":
form = PostForm(request.POST, request.FILES)
# request.FILES necessary so that file is submitted
# also required to add enctype to the form
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect('home')
context = {'form': form}
return render(request, 'my8gag/post_form.html', context)
Couldn't find anything about this in the documentation or here on SO, so would appreciate any kind of help/hints! Thanks in advance.
Allow the field to be null
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField()
profile_image = CloudinaryField('profile_image', null=True, default=None, blank=True)
def __str__(self):
return self.user.username

Django, viewing uploaded files and videos

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.

Image upload in Django, namerror

Getting NameError (global name FileUploadHandler not defined). Here is the model:
class FileUploadHandler(models.Model):
title = models.CharField(max_length=100)
file = models.ImageField(upload_to="wiki/static/")
And the view:
def image_upload(request):
if request.method == 'POST':
form = UploadImageForm(request.POST, request.FILES)
if form.is_valid():
FileUploadHandler(request.FILES['image'])
return render_to_response('wiki/gallery.html')
else:
form = UploadImageForm()
return render_to_response('wiki/gallery.html', RequestContext(request, {'form': form}))
What am I missing?
At the top of your view file, type:
from models import FileUploadHandler
This is assuming you have the standard views.py and models.py file structure where both are in the same directory.

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 image uploading

I have a problem with image uploading. For now, chosen image file is not copied to destination directory and path to this file is not added to database.
I'm giving my code below:
models.py:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
avatar = models.ImageField(upload_to="avatar/")
form.py
class ProfileEditionForm(ModelForm):
class Meta:
model = UserProfile
exclude = ('user')
view.py:
def index(request):
if request.user.is_authenticated():
user = User.objects.get(pk=request.user.id)
if request.method == "POST":
form = ProfileEditionForm(request.POST, request.FILES, instance=user)
if form.is_valid():
form.save()
#return HttpResponseRedirect(reverse('profile_edit'))
else:
form = ProfileEditionForm(instance=user)
return direct_to_template(request, 'profile_edit.html', { 'form' : form })
else:
return HttpResponseRedirect(reverse('main_page'))
Thanks in advance for help.
https://docs.djangoproject.com/en/dev/topics/http/file-uploads/
your form should have the enctype="multipart/form-data" or request.FILES won't have any data stream associated
your ModelForm is bound to UserProfile model, but your are instantiating it with instance=user.
PS: request.user is User.objects.get(pk=request.user.id)

Categories