I have recently started using Cloudinary for media storage.
I have a Profile model with image and cover image fields
Without Cloudinary
Before changing to cloudinary media storage the model looked like this:
class Profile(models.Model):
user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)
# setup without Cloudinary
image = models.ImageField(default='profile_image/default.jpg', upload_to='profile_image', blank=False)
cover_image = models.ImageField(default='cover_image/default.jpg', upload_to='cover_image', blank=False)
It allowed me to set default image for both fields.
With Cloudinary
Now, after adding Cloudinary, it looks like this:
class Profile(models.Model):
user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)
# setup with Cloudinary
image = CloudinaryField('image')
cover_image = CloudinaryField('cover_image')
I want to be able to set default images for both fields.
Here are relevant libraries' versions
Django==2.1.5
cloudinary==1.17.0
django-cloudinary-storage==0.2.3
olefile==0.46
cloudinary-cli==0.3.4
Cloudinary now supports delivering default images when a requested image does not exist.
Assuming a case where you want a default image displayed in a page, I have limited knowledge on whether you can do it from the model, you can implement this functionality in the view that renders that page e.g
CloudinaryImage("if_set_image.jpg").image(transformation=[
'default_image': "default_image.png"
])
For more information read this article or the documentation
Given that you need to work with cloudinary, you can also consider retaining the default django provided ImageField (hence easily set the default option) and use cloudinary.uploader.upload("my_image.jpg") to upload your images to cloudinary in your view.
Related
Is there anyway where we can build logic Using django rest framework
where user can add blog with multiple images and content accordingly and when saved
and retrieved it should be able to display the same kind of UI depening up on the frontend app
same like medium platform
Note:
My question isn't about adding multiple images and content using Rest framework
but its about fetching and displaying the data based on how user sent it the server
For eg:
<Image>
content for that image
<Image2>
content for this image
i just want to know how to associate those images to that content
i want to add content to that image
or is there anyway where we can store image and all the content exacty and save it in TextField
I've searched a lot about this but unfortunately I've not found a way to make this happen
Read about relationships in Django (and SQL in general)
django relations
it sounds like you're looking for something like the following:
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
# Always override the user model provided by Django when starting a project. the docs themselves state that.
pass
class Image(models.Model):
image = models.ImageField()
added = models.DateTimeField(auto_now_add=True)
# using get_user_model to get the User model, always better then referencing User directly
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name="user_images",
null=False,
blank=False
)
class ImageContent(models.Model):
title = models.CharField(max_length=140, null=False, blank=False)
content = models.TextField(max_length=500)
image = models.OneToOneField(Image, on_delete=models.CASCADE, null=False, blank=False)
Some notes:
I haven't dealt myself with Images field But I remember it does require a special library (pillow).
getting the data in a certain order should be easy enough if you understand the queryset object:
queryset link
using stuff like order_by will help you return the response in the order you like.
the models I've written here are not the only way to achieve the goal you've set, I strongly recommend reading about relations and models in Django.
I have a blog on django on which any public can post. In post content I am using django-ckeditor RichTextUploadingField.
There is button Browse server for images in ckeditor, that let users browse images of server's upload directory and embed images in post.
But i want to restrict public from browsing images on server when they make post. They should be able upload images only, not browse every image on server that is uploaded.
Here is my models.py
class Article(models.Model):
title = models.CharField(max_length = 200)
content = RichTextUploadingField()
author = models.ForeignKey(User, on_delete= models.CASCADE, null=True)
def __str__(self):
return self.title
Forms.py
class ArticleForm(ModelForm):
class Meta:
model = Article
widgets = {
'content': RichTextUploadingField()
}
A direct setting to remove this functionality isnt provided but CKEDITOR_RESTRICT_BY_USER = True could be used to achieve the same.
Reference from the documentation:
Set the CKEDITOR_RESTRICT_BY_USER setting to True in the project's
settings.py file (default False). This restricts access to uploaded
images to the uploading user (e.g. each user only sees and uploads
their own images). Upload paths are prefixed by the string returned by
get_username. If CKEDITOR_RESTRICT_BY_USER is set to a string, the
named property is used instead. Superusers can still see all images.
NOTE: This restriction is only enforced within the CKEditor media
browser.
I want to upload images not from files but from url's that are submitted by the user, via a put call with a payload like {"image_url":"http://example.com/1.jpg"}.
What is the recommended way of doing this with DRF?
(So far my only option is to reimplement everything manually within my model view set. Is ther any better solution?)
UPDATE:
my serializer was:
class Person(models.Model):
image = models.ImageField() #...
class PersonSerializer(serializers.ModelSerializer):
image = serializers.ImageField(required=False)
class Meta:
model = Person
fields = ('image',)
Does the image actually need to be downloaded to the server? Can you not just save the URL in a CharField and pass it over to the client side for their browser to download? <img src="{{ your_model.image_url }}>". Doing it like this would save alot of storage space on the server and mitigate many security checks required by this process which include making sure the image is not too large! A user could provide an image that is 100GB, which could crash the server. By downloading the image from a web URL and serving it yourself, you are effectively hosting an image which is already being hosted elsewhere.
HOWEVER, If you do wish to download the image, use a python based HTTP request library to download the image. Then use an ImageField in your model to handle the storage and recall of the image. https://docs.djangoproject.com/en/dev/ref/models/fields/#imagefield
If you wished to perform the storage manually, you could save the file in a folder on the server, then save a link to this file in a CharField. Though as far as I am aware, this is essentially what the ImageField would do though for you.
Well, what I ended up doing is using URLField at serialization.
class Person(models.Model):
image = models.ImageField()
class PersonSerializer(serializers.ModelSerializer):
image = serializers.URLField()
# with a custom field serializer it is possible
# to make this field behave both as URLField (handling links)
# and as ImageField (handling files)
class Meta:
model = Person
fields = ('image',)
def save(self):
# handles the upload if the image url is external.
Is there any possible way to resize the original image in the views.py and then load the resized image from the views to the template? I tried using sorl-thumbnail and easy_thumbnail, they works great, but I don't know why, somehow whenever I upload it using the apache server, the server only loads the images uploaded by the django's inbuilt server, and when I load the page again with the django's inbuilt server it loads the uploaded image nicely. So, is there anyway that I can resize the image in the views itself, and then load it in the templates? And if there is, please kindly guide me how do I do it. Thank you!
models.py
class Status(models.Model):
status = models.TextField()
image = ImageField(upload_to=get_upload_file_name, blank=True)
pub_date = models.DateTimeField(default=datetime.now)
creator = models.ForeignKey(User, related_name="creator_set")
likes = models.ManyToManyField(User, through="Like")
class Meta:
ordering = ['-pub_date']
verbose_name_plural = ('Status')
def __unicode__(self):
return self.status
Me, too, I don't understand your problem with generating thumbnails in the template. But if you want to create them in the view (or anywhere else in the python code), that will be possible with sorl thumbnail. In the sorl thumbnail docs, there's the following low level api example:
from sorl.thumbnail import get_thumbnail
im = get_thumbnail(my_file, '100x100', crop='center', quality=99)
I'm trying to create a field in a model, that should store an image for a registered user.
This image should be renamed and stored in a separate user directory like media/users/10/photo.jpeg.
I've searched a lot, but still can't find how to do it cleanly and correctly. It seems to me that many sites require the same functionality and this should be in django docs, but it is not.
You want to use the "upload_to" option on an ImageField
#models.py
import os
def get_image_path(instance, filename):
return os.path.join('photos', str(instance.id), filename)
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
profile_image = ImageField(upload_to=get_image_path, blank=True, null=True)
This is code directly from a project of mine. The uploaded image goes to /MEDIA_ROOT/photos/<user_id>/filename
For what you want, just change the 'photos' string to 'users' in def get_image_path
Here is the small bit about it in the docs, under FileField details
I suggest you to look into django-photologue. Its a django app with all image managment, uploading and storing already done!
More about at: http://code.google.com/p/django-photologue/
You'll need to make a model that has a foreign key to the User model, where you can have an image field for the User. I would not recommend modifying the User model itself.