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.
Related
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
})
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.
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
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)
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')