Resize and Rename Image in Django UpdateView - django

I want to be able to create 3 different sizes of an image when a user uploads an image in an UpdateView in Django.
I also want to be able to rename the file they upload to something like username_thumb_01.jpg, username_original_01.jpg, username_medium_01.jpg.
views.py
class UserProfileEditView(UpdateView):
model = UserProfile
form_class = UserProfileForm
template_name = "edit_profile.html"
forms.py
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, unique=True)
website = models.URLField(null=True, blank=True)
avatar = models.ImageField(upload_to="user-photos", null=True, blank=True)
I tried to add something like the following to my UserProfileEditView but it didnt work and I wasnt sure If i was on the right track.
def form_valid(self, form):
if self.request.files:
filename= join(settings.MEDIA_ROOT, profile.avatar.name)
im = Image.open(filename)
im.thumbnail((160,160), Image.ANTIALIAS)
im.save(imfn, "JPEG")
form.save
Has anyone done this before? How can I accomplish it ?

Although their approach is different I suggest using sorl-thumbnail. Instead of creating the images when they are uploaded what this does is creates them when they are required and then caches them using whatever caching system you specify.

I do this by using a custom image field. The code for it is available on github at https://github.com/hellsgate1001/django-thumbs.
I didn't create this, I forked it to add a bit more flexibility to the thumbnail creation and also to ensure it works with Django 1.5

Related

Why RelatedObjectDoesNotExist is thrown when trying to add an entery from the django admin?

In my models, I have the ImageAlbum model and Image model. In the Image model, I have a ForeignKey field to the ImageAlbum. This code is actually recommended from this article.
class ImageAlbum(models.Model):
def __str__(self):
return str(self.pk)
class Image(models.Model):
name = models.CharField(max_length=255)
image = models.ImageField(upload_to=get_upload_path)
default = models.BooleanField(default=False)
thumbnail = models.ImageField(upload_to=get_thumbnail_path, default='default/default_thumbnail.jpg')
album = models.ForeignKey(ImageAlbum, on_delete=models.CASCADE)
I registered the models in the admin and the Image form looks like that:
And after I hit save, the following exception occurs:
Your ImageAlbum Model should look like this .
class ImageAlbum(models.Model):
image = models.ImageField(upload_to='images/', blank=True) # new
def __str__(self):
return str(self.pk)
Migrate first and then Check again this would work.
I experienced the same issue, in my case it had to do with the migrations. I re-ran migrations afresh after clearing them out and that solved the issue you are highlighting. Of cause this was on a local dev environment with a SQLite db setup, you may not have such a luxury in production.

Django. Rest framework. How to generate the same tags?

Digging out the features of Django Rest Framework, I constantly come across difficulties. Here it is now. I have photos, each photo has a separate field (photo_1, photo_2, photo_3, etc). These photos need to be uploaded to the same tags, like this:
<image>photo_1_url</image>
<image>photo_2_url</image>
<image>photo_3_url</image>
My models.py:
photo_1 = models.ImageField(upload_to=image, blank=True)
photo_2 = models.ImageField(upload_to=image, blank=True)
photo_3 = models.ImageField(upload_to=image, blank=True)
My views.py:
class SerializerImage(serializers.ModelSerializer):
class Meta:
model = kv
fields = ['photo_1', 'photo_2', 'photo_3']
In xml I get the following fields and this is wrong:
<photo_1></photo_1>
<photo_2></photo_2>
<photo_3></photo_3>
I need to place all the photos under the tag <image>.
Help advice! How to make all images under one tag. I tried through self.fields.update. Tag photo_1 changes to an image, but this can only be done once. Two tags with the same name are not displayed.
Thank!
UPDATE:
Supplement for Sreeram.
After your advice on the output, I get the following result:
<example_field>
<image>photo_1_url</image>
<image>photo_2_url</image>
<image>photo_3_url</image>
</example_field>
My expected result is independent <image> tags, without nesting. Like this:
<image>photo_1_url</image>
<image>photo_2_url</image>
<image>photo_3_url</image>
Use SerializerMethodField
from rest_framework import serializers
class SerializerImage(serializers.ModelSerializer):
example_field = serializers.SerializerMethodField()
class Meta:
model = kv
fields = ['example_field']
def get_example_field(self, obj):
#do your queries, edits here.
string = f'<image>{obj.photo_1},{obj.photo_2},{obj.photo_3}</image>'
return string

django admin foreign key to file field and many to many field

I have a model Teacher which has following data:
class Teacher(models.Model):
name = models.CharField(max_length=100)
thumbnail = models.ForeignKey(Thumbnail)
class Thumbnail(models.Model):
thumbnail = models.FileField(upload_to=upload_to)
class TeacherAdmin(admin.ModelAdmin):
list_display = ('name',)
Here I want to relate all the thumbnail in my project to Thumbnail field. In my admin it shows me a dropdown of thumbnail while I want to add the thumbnail from admin.
Is it possible that I can upload from admin too?
Also what can I do in the case like :
class Teacher(models.Model):
name = models.CharField(max_length=100)
thumbnail = models.ManyToManyField(Thumbnail)
If I want to add multiple Images.
The only issue I am having is on admin side. Client side can be handles from regular forms.
Need suggestions and Ideas

Django Admin Select Objects based on ManyToMany Relationship

I'm working on building a django app that extends the Mezzanine project. Mezzanine has a Gallery app (photos). I'd like to create "portfolio" page that acts as a landing page which has a single image and link to each gallery page.
Each gallery (Gallery) can have multiple images (GalleryImage). I'd like to via the admin select a gallery, then select an image to be displayed. However, I can't seem to figure out what to do.
Here's my model:
class GalleriesThumb(models.Model):
relatedlandingpage = models.ForeignKey(LandingPage)
relatedgallery = models.ForeignKey(Galleries)
thumb = models.ManyToManyField(GalleryImage)
def __unicode__(self):
return self.name
class Galleries(models.Model):
landingpage = models.ForeignKey(LandingPage)
tagline = models.CharField(max_length=100)
galleries = models.ManyToManyField(Gallery)
def __unicode__(self):
return self.name
class LandingPage(models.Model):
gallerytitle = models.CharField(max_length=200)
def __unicode__(self):
return self.name
My admin is something like:
class GalleryInline(admin.InlineModelAdmin)
model = Galleries
model = GalleriesThumb
list_display = galleries
list_display = thumb
class LangingPageAdmin(admin.ModelAdmin):
fieldsets = (
(None, {
'fields': ('gallerytitle')
})
inlines = [GalleryInline,]
I realized that this won't do what i want, but how do I get the list_display on the the images that are related to Galleries. I'm pretty sure it needs to be a method, or am I taking a completing wrong approach if the selections that are made will be defining the content on the page. (I realize that I'm also missing my fields to store the selection in.)
I'm sorry if this a dumb question, but this my first real world attempt an app.
I think this link will resolve your problem
Django 1.2.1 Inline Admin for Many To Many Fields
class GalleryInline(admin.InlineModelAdmin)
model = Galleries.galleries.through

How to access model data when overriding Django admin templates?

sorry if this is an obvious question but I have been searching for a few days and have not been able to come up with a result.
I am creating a simple photo gallery app. There are four galleries, each containing a photo (the photo consists of a 'before' image, 'after' image and caption). I am trying to use django-admin to allow users to click on a gallery and then add photos.
I am using a TabularInline to edit the photos within each gallery. In addition to the default columns on the TabularInline, I would like to add a column that shows a thumbnail preview of the 'before' photo and 'after' photo (I am using easy-thumbnails for this). After much searching, it seems like the best way to do this is to override the django-admin tabularInline.html template and add the column myself - so I created another copy and am trying to edit it now.
What I would like to do is simply reference the Photo object within the Django admin template that I am overriding - but I don't know the appropriate tag to use. I need the reference so I can use it in conjunction with the easy-thumbnails thumbnail tag ... but for the life of me I cannot figure out the template tag that references the object. I have tried iterating through the ModelForm, FormSet, and FieldSet objects but none seem to give me a direct reference to the object.
# models.py
class Gallery(models.Model):
name = models.CharField(max_length=200)
url = models.CharField(max_length=200)
desc = models.TextField()
def __unicode__(self):
return self.name
class Photo(models.Model):
gallery = models.ForeignKey(Gallery)
before = models.ImageField(upload_to='gallery')
after = models.ImageField(upload_to='gallery')
caption = models.CharField(max_length=1000)
order = models.IntegerField(blank = True, null = True)
def __unicode__(self):
return "Photo " + str(self.order)
# admin.py
class GalleryForm(forms.ModelForm):
model = Gallery
class Media:
js = (
'/assets/js/jquery-1.4.2.min.js',
'/assets/js/jquery-ui-1.8.2.custom.min-admin-sortable.js',
'/assets/js/menu-sort.js',
)
class PhotoInline(admin.TabularInline):
model = Photo
extra = 1
template = "admin/tabular-thumbnails.html"
admin.site.register(Gallery,
inlines=[PhotoInline],
form = GalleryForm)
Thanks so much in advance and please let me know if there's any additional information I can offer. I am using Django 1.1
In Django 2.1 {{adminform.form.instance.field_name}} worked for me.
{{ form.instance }} will always be the model instance associated with a modelform, assuming there is one.
(Note that ``{{ formset.instance }}` is the instance of the parent model in an inline formset).