In Wagtail, How to add custom folder in Media and sync it into the database (Example) ?
NOTE: The Wagtail's Collection function is good, but for more than 1000 images/documents into a single folder will be pretty awkward to manage for I in the future (Ex: migration,...), so there is nothing to mention about Collection function in this question.
# If in Django (models.py) works:
class post(models.Model):
img = models.ImageField(upload_to='posts')
# So how in Wagtail (models.py) works:
class Posts(models.Model):
img = models.ForeignKey(
"wagtailimages.Image",
👉🏽 upload_to='posts', # How to add this line correctly ?
on_delete=models.SET_NULL,
null=True,
blank=False,
related_name="+",
)
Idea for Media Folder in Wagtail:
Media
authors
images
original_images
posts
images
original_images
...
If you want specific folders for specific models, you can set a specific folder by customizing the upload_to attribute in the model. Otherwise, the only option I know is to create collections.
Related
I need a way to have different upload and download URLs for ImageField. I want to upload the image to AWS S3 and while accessing the image I want the image to route through CDN (in my case Fastly).
def get_avatar_upload_path(identity, filename):
file_ext = filename.split('.')[-1]
file_name = f'{uuid.uuid4()}.{file_ext}'
return f'{settings.AWS_MEDIA_PREFIX}{identity.uuid}/{file_name}'
class Identity(identity_revision_base):
"""
Identity model. Ties a user to a chat identity.
"""
badges = models.ManyToManyField(Badge, blank=True)
key = models.UUIDField(_("key"), unique=True, default=uuid.uuid4)
uuid = models.UUIDField(_("UUID"), unique=True, default=uuid.uuid4)
avatar = models.ImageField(upload_to=get_avatar_upload_path, blank=True)
user = models.ForeignKey(
to=settings.AUTH_USER_MODEL,
blank=True,
null=True,
on_delete=models.SET_NULL,
related_name="+",
)
Just like I am specifying upload path in ImageField, I would like a way to do something similar for accessing Image. It also seems that I cannot modify avatar.url once it is created. Is there any way around?
If there is any way, I can override the Model's behaviour to modify the url while accessing.
Did you check django-storages? It takes care of uploading to object store and returns CDN URLs for downloading. Fastly is S3 compatible so it should work.
In general you can also also use model methods with property decorator for getting a custom calculated value from model instances.
I have an app called 'Product' with the following models.py:
class Product(models.Model):
product_id = models.CharField(max_length=50)
pub_date = models.DateTimeField(default=datetime.now)
title = models.CharField(max_length=255)
price = models.DecimalField(max_digits=8, decimal_places=2)
user = models.ForeignKey(User, on_delete=models.CASCADE)
featured = models.BooleanField(default=False)
I want to have two separate sections in Django Admin: Products and Featured Products, depending if featured = True or False.
So by default all products are listed under the Products section. But if featured = True they will be moved to Featured Products section. Can you please help me how to do that? Thanks in advance.
Three steps:
Write a proxy model for model Product.
Change the default manager to only returns featured products.
Register your proxy model in the admin like any other model.
You can read more about it here: Using Proxy Models to Customize the Django Admin
There are a couple of ways to do this. The simplest perhaps is to create a database view, and then encapsulate it using a django model. You can create a view like so in your database console:
CREATE VIEW view_name AS
SELECT columns
FROM tables
[WHERE conditions];
Once you have done that, you can reference the view in django like so:
class FeaturedProduct(modes.Model):
attr1 = models.CharField()
class Meta:
managed = False
db_table = '<name of your view here>'
Make sure that managed is set to False. Here is the relevant documentation for that. You want to do that because django is not creating this model for you, but rather you are creating it yourself.
Another way to do this would be to create a custom Manager. These managers allow you to modify the objects attribute of your model, allowing you to set a queryset that you want. I think you'd want to take a look at the Manager documentation and you can take a look at defining custom querysets for your objects.
I have two database which are OneToManyRelationship as shown below.
I am preparing interface for Data to be uploaded.
I want to specify the project attribute in Data model by inputting the url of the Project path like http://project/13.
Does anyone know how I can construct the relationship from url input of parent data?
Models.py
class Project(models.Model):
project = models.CharField(max_length=50, blank=True)
version = models.IntegerField(default=0)
class Data(models.Model):
project=models.ForeignKey(project)
csv=models.FileField(upload_to=dir_path)
If url in Project model sits in project field then you can do something like
# since project attribute is not unique, several ones can match so we pick first
project_object = Project.objects.filter(project=url).first()
if not project_object:
# error cant find it
Data.objects.create(
project=project_object,
csv=...,
)
I am creating the website which contains 10k movies and it has an attribute called movies_logo which stores the logo of the respected movie .So is there any way so that I can upload all the logo of the respected movies in one go because uploading logo of each movie will take lot of time.This is my models.py.
from django.contrib.auth.models import Permission, User
from django.db import models
from decimal import Decimal
class Picture(models.Model):
user = models.ForeignKey(User, default=1)
picture_id = models.IntegerField(default=0)
picture_title = models.CharField(max_length=500)
genres = models.CharField(max_length=1000)
ratings = models.DecimalField(max_digits=10,decimal_places=1)
picture_logo = models.ImageField()
def __str__(self):
return self.picture_title
If you don't the save location for the images, then upload a single picture and see where it gets stored and with what name. If you don't like the naming, you can change it. Once that is figured out, you can simply go to your mysql command-line, and set the image field in the database to the file name and structure you have decided and then upload / move the images to the correct location. If you want, you can use a for loop to set the image field instead of writing SQL.
Whenever I visit the path for an uploaded image in the admin, I get a 404. The image is successfully uploaded in the specified path but I don't know what URL structure to use to access the image. There is not URL structure specified yet for the image (that's what I want to know, or am I missing anything else?). Here are the details:
My models.py
class Product(models.Model):
category = models.ForeignKey('CatalogCategory', related_name='products')
name = models.CharField(max_length=300)
slug = models.SlugField(max_length=150)
description = models.ImageField(upload_to='product_photo', blank=True)
manufacturer = models.CharField(max_length=300, blank=True)
price_in_dollars = models.DecimalField(max_digits=6, decimal_places=2)
this is the error:
Request
URL: http://localhost:8000/admin/products/product/1/product_photo/soy_candles.jpg/
product object with primary key
u'1/product_photo/soy_candles.jpg'
does not exist.
this is the dir struct
product_photo
products
->templates
->models.py
->views.py
->...
manage.py
settings.py
urls.py
EDIT
I have not touched the details regarding the admin on the settings
Your MEDIA_URL defines this.
You either have it defined to '' and the admin is generating a relative URL or you have it set to http://localhost:8000/admin/products/product/1/ which is unlikely :P