400 error on django filefield model save - python

I'm using django 1.6.5 on python 2.7, and am trying to upload images with a form. My MEDIA_URL is '/uploads', MEDIA_ROOT='...../projectroot/uploads'.
My model:
class Picture(models.Model):
person = models.ForeignKey(User)
image = models.ImageField(upload_to='/images')
My Form field:
images = forms.ImageField(widget=forms.FileInput(), required=False)
My form saving:
image = self.cleaned_data['images']
picture = Picture(park=model, image=image)
picture.save()
I have tried setting the uploads folder permissions to 777 recursively, so django definitely has write access, but that didn't work. Somebody said the enctype on the form mattered, so I've set that to "multipart/form-data".
If it helps, only the actual saving creates the error (although that may have something to do with django just using lazy functions)

Related

How to edit formset that has multiple forms inside related via generic foreign to the model of the current edit view?

In my recent project I had to create a generic model with a single file field, because the idea was to use multiple file uploads across multiple system models.
For this I created this generic model with generic foreign key and in the add view I create a formset with the extra = 1 field and in the template via jquery I add forms inside my formset.
In addition it works quietly, but I'm not able to adjust my edit view.
In my edit view I try it:
ModelGenericFormset = modelformset_factory(
ModelsFileGeneric,
form=AddModelsGenericForm
)
query_files = ModelsFileGeneric.objects.filter(
object_id=model_related_to_generic_model_with_file_field.id,
)
files = ModelGenericFormset(queryset=query_files)
and in request.post:
files_form_set = ModelGenericFormset(
request.POST,
request.FILES
)
for file_form in files_form_set:
file = file_form.save(commit=False)
setattr(
'upload_destination',
'path_to_upload'
)
file.content_object = model_related_to_generic_model_with_file_field
file.save()
An observation:
As this model where the file field is is an extremely generic model (for this reason the use of the generic foreign key), I also need at runtime (in the save in view after the post) to change the upload_to attribute of the field (this already Was fixed and works ok).
I make this edition of the "upload_to" attribute because depending on the model to which I am sending multiple files, it will vary the path from where the files will be saved.
But in save of the edit view this error occurs:
The ModelsFileGeneric could not be changed because the data didn't validate.
And the error is in:
file = file_form.save(commit=False)
I don't know what to do anymore. Thanks!

Errors using Django Awesome Avatar

Have been trying to solve an issue using Django awesome avatar. I have used the AvatarField() in my models to save the profile pic in the UserProfile model.
avatar = AvatarField(upload_to=upload_profile, width=100, height=100,default = 'profiles/profile.jpg',)
Have also used a ModelForm to render the field to a form that is shown on the templates
avatar = avatar_forms.AvatarField()
When I try to access the user profile in admin and save, it throws an error:
'ImageFieldFile' object has no attribute '__getitem__'
Also, when I select a photo on the form in template, it does not show the crop tool that am supposed to use to resize the image.
Are you trying to access the file name?
You should use something like this:
def __unicode__(self):
return unicode(self.image_location)
source: Django image field throws TypeError

Error when using django-admin-multiupload and django-imagekit together

At the moment I'm on my way using the django-imagekit to show thumbnails in an image-heavy view of a gallery app. For this purpose I'm using the 'model-method', means I'm creating the thumbnails within the model.
Now with the comfort of the admin in mind (upload multiple picture at once) I also want to implement a multi-upload form in the admin-view. To ease things a little bit I tried to use an app I found on GitHub, django-admin-multiupload (I'm not able to link to it because of my low reputations but that's the exact name for it on GitHub).
When I only use django-imagekit, everything works fine and I get nice thumbnails, just like expected. When I only use django-admin-multiupload, everything works fine and I'm able to upload multiple images just like expected.
The problem starts when I'm using both apps at the same time. The multiupload works still fine but when I'm opening the view, and actually implementing the thumbnail (only using both and not implementing the thumbnail works fine), where the thumbnails should be shown I will get the following error:
OSError at /gallery/ - decoder jpeg not available
You can see the full error here: http://pastebin.com/gtVYEeG7
My confusion starts when starting only the single app and it works. So as far as my knowledge goes, all PIL issues could not be present.
To provide some more information: I'm using a virtualENV with the following list of packages:
pip
django
PIL
pilkit
django-imagekit
django-amdin-multiupload
To also provide some of my implementet code, here it is:
File: models.py
class Image(models.Model):
"""the model for the images"""
# the foreign key from the event
event = models.ForeignKey('Event', related_name='images',
blank=True, null=True)
# the image itself
# file = models.FileField('File', upload_to='gallery/images/')
file = models.ImageField('File', upload_to='gallery/images/')
image_thumbnail = ImageSpecField(source='file',
processors=[
ResizeToFill(300, 250)
],
format='JPEG',
options={'quality': 40})
# image title to represent it in the admin interface
image_name = models.CharField(max_length=35, default='img')
# publication date of the image
pub_date = models.DateTimeField('date published',
auto_now_add=True)
# for a better representation of the image
def __str__(self):
return self.image_name
File: admin.py
(this one is mostly as suggested in the example from the django-admin-multiupload repo, can be viewed here: https://github.com/gkuhn1/django-admin-multiupload/blob/master/example/gallery/admin.py)
from django.contrib import admin
from django.shortcuts import get_object_or_404
from gallery.models import Event, Image
from multiupload.admin import MultiUploadAdmin
# Register your models here.
# allows inline add of single images
class ImageInlineAdmin(admin.TabularInline):
model = Image
# used to define the process_uploaded_file function
# so it will not be duplicated in the Admin-Classes
class GalleryMultiuploadMixing(object):
def process_uploaded_file(self, uploaded, event, request):
image = event.images.create(file=uploaded)
return {
'url': image.file.url,
'thumbnail': image.file.url,
'id': image.id,
'name': image.image_name
}
# admin class for event model
class EventAdmin(GalleryMultiuploadMixing, MultiUploadAdmin):
inlines = [ImageInlineAdmin,]
multiupload_form = True
multiupload_list = False
def delete_file(self, pk, request):
obj = get_object_or_404(Image, pk=pk)
return obj.delete()
admin.site.register(Event, EventAdmin)
# admin class for image model
class ImageAdmin(GalleryMultiuploadMixing, MultiUploadAdmin):
multiupload_form = False
multiupload_list = True
admin.site.register(Image, ImageAdmin)
File: index.html
<td><img class="img-responsive" src="{{ image.image_thumbnail.url }}" /></td>
If there is any need for additional information please don't hesitate to ask.
Thank you in advance and I appreciate any help.
Edit: Today I tried another way and recognized that the error is only appearing to images that were uploaded with the django-admin-multiupload and not if only images are shown that were uploaded with the normal method. Maybe this could help to find a solution.
This error was mainly caused by a broken database that could be fixed by going back to an older version and reimplementing the new code. So there is no problem in django-admin-multiupload or django-imagekit.

Django - Problems with PDF upload

I got another problem with Django. I want to upload an PDF with an Form in the template, when I click upload in my form, this happens:
Cannot assign "<InMemoryUploadedFile: thebook.pdf (application/pdf)>": "Product.book" must be a "File" instance.
This is the line in my model
book = FilerFileField(null=true,blank=true)
This is the line in my form
book = forms.FileField(label=u"Book Upload")
Django's forms.FileField expects an UploadedFile. Whereby the FilerFileField is actually a subclasses of django.db.models.ForeignKey. Therefor you should use a ChoiceField at your form.
book = forms.ModelChoiceField(queryset=filer.models.File.objects.all())
See also django-filer's usage notes and django's docs on the ModelChoiceField:
http://django-filer.readthedocs.org/en/latest/usage.html
https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield

Attach an image into a Django Model

Making a basic Q&A site and want to associate each question with an image (admin uploaded) and if there is no respective image, puts it with a default "No Image" placeholder.
I have two models, Question and Answer (see below). Each question needs to have an image associated with it, so I thought the best way was to attach attribute ImageField with the Question model.
#models.py
class Question(models.Model):
title = models.CharField(max_length = 500)
picture = models.ImageField(height_field = '250',
width_field = '200',
upload_to = 'images')
def __unicode__(self):
return self.title
When I runserver though, tells me to download Python Imaging Library, and when I do get an error (different problem).
Taking a step back, what is the best way to add an image to a model in Django?
Forget PIL...
Use a location URL DB entry. Instead of having an ImageField(), use
picturepath = models.CharField(255)
that contains a URL to the static location of the image.
so if STATIC_URL = "http://127.0.0.1/static/"
and picturepath = "images/poots.png"
Then, pass that information along in the view, and use this in the template:
<img src="{{ STATIC_URL }}{{ question.picturepath }}">
will provide
<img src="http://127.0.0.1/static/images/poots.png">

Categories