I have a model for my user and another model for music style. In my model of musical styles, I need to put the image under a name other than the original name.
The new name I would like is the 'email of the user who is saving' + '_' + 'milliseconds'.
Staying in this format:
'test#gmail.com_1621196336'
Model User:
class CustomUser(AbstractUser):
username = None
id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False)
email = models.EmailField('E-mail', unique=True, null=False)
Model Music Styles:
class MusicStyle(models.Model):
id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False)
name = models.CharField(max_length=150, null=False, blank=False)
image_link = models.FileField(upload_to='musics/thumbnail_images/##CUSTOM_NAME##')
Musical style is in a different model from the user model.
How to do this?
i didnt understand what the field with milliseconde is or what is supposed to do so i replaced it with with email and music_style name, here is how you can name your images, you can adjust it as you want
def upload_location(instance, filename):
filebase, extension = filename.split('.')
return 'musics/thumbnail_images/%s_%s.%s' % (instance.user.email,instance.name, extension)
class MusicStyle(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
name = models.CharField(max_length=150, null=False, blank=False)
image_link = models.FileField(upload_to=upload_location)
If you want to set custom filename for your files you can do this:
def image_upload_to(instance, filename):
# You can access to your model fields with instance for example: instance.name
return f"musics/thumbnail_images/{filename}"
class MusicStyle(models.Model):
id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False)
name = models.CharField(max_length=150, null=False, blank=False)
image_link = models.FileField(upload_to=image_upload_to)
Related
Suppose I have a model below :
class Post(MainProcess, TimeStampedModel, SoftDeletionModel, models.Model):
"""Post model."""
slug = models.SlugField(default=uuid.uuid4(), unique=True, max_length=100)
uuid = models.UUIDField(unique=True, max_length=500,
default=uuid.uuid4,
editable=False,
db_index=True, blank=False, null=False)
title = models.CharField(_('Title'), max_length=100, blank=False,
null=False)
image = models.ImageField(_('Image'), upload_to='blog_images', null=True,
max_length=900, blank=True)
I wanted to override the image field values without using the save() function, what is the best approach here which will be efficient.
I'm trying to save unique name in the database but the problem I can save the same with different letters, for example I can save (IT, it, iT, It) I don't want to save it like that.
Model:
class Service(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=127, unique=True, null=False, blank=False) # that field
is_active = models.BooleanField(default=True)
is_deleted = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(
"accounts.User",
on_delete=SET_NULL,
blank=False,
null=True,
related_name="service_created_by",
)
def __str__(self):
return f"{self.name}"
A very simple solution:
class Service(models.Model):
name = models.CharField(max_length=50, unique=True)
....
def clean(self):
self.name = self.name.capitalize()
this one helped me
class Service(models.Model):
name = models.CharField(max_length=50, unique=True, null=False, blank=False)
....
class Meta:
constraints = [
models.UniqueConstraint(Lower("name"), name="unique_name"),
]
def clean(self):
self.name = self.name.capitalize()
it only happens when I create new chatroom with the same admin
this is what I wrote in my models.py
class ChatRoom(models.Model):
id = models.UUIDField(primary_key=True, unique=True,
default=uuid.uuid4, editable=False)
name = models.CharField(max_length=100, null=False, blank=True)
users = models.ManyToManyField(User, through='Membership')
admin = models.ForeignKey(
User, null=False, blank=False, on_delete=models.CASCADE, related_name='admin')
date_created = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Membership(models.Model):
id = models.UUIDField(primary_key=True, unique=True,
default=uuid.uuid4, editable=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
chatroom = models.ForeignKey(ChatRoom, on_delete=models.CASCADE)
date_joined = models.DateTimeField(auto_now=True, null=False, blank=False)
def __str__(self):
return self.user
class Meta:
unique_together = [['user', 'chatroom']]
when i write this in the shell:
from .main.models import ChatRoom,Membership
from django.contrib.auth.models import User
user = User.objects.get(username = 'someone')
chatroom = ChatRoom(admin = user, name = 'something')
chatroom.save()
chatroom2 = ChatRoom(admin = user, name = 'somethingElse')
chatroom2.save()
after i save chatroom2 i get this error : django.db.utils.IntegrityError: UNIQUE constraint failed: main_chatroom.admin_id
can anyone help me?
so it turned out that i did something that made all migrations does not have any affect on the database
so i created new project and copied all my code to the new project( yes i know this is not the right way to do things but it was the easiest way for me) and everything now works great
I'm trying to create an address form with multiple address, where the user can choose home or shipping address. I have the current model:
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
class Address(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60, default="Miami")
state = models.CharField(max_length=30, default="Florida")
zipcode = models.CharField(max_length=5, default="33165")
country = models.CharField(max_length=50)
class Meta:
verbose_name = 'Address'
verbose_name_plural = 'Address'
def __str__(self):
return self.name
So I was wondering if that's correct.
Anyway, I was wondering how with the current model I can create a view so I can have the address form. Using a normal model would be "easy" but how can I do it using the through option in the model?
Could someone lend me a hand please?
Thank you
use a foreign key to point to your address model:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
nick_name = models.CharField('Nick name', max_length=30, blank=True, default='')
bio = models.TextField(max_length=500, blank=True)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
addresses = models.ForeignKey(Address) # <-- fix here
Hope this helps!
You should declare ForeignKey with '<app>.<model>' format:
class AddressType(models.Model):
address = models.ForeignKey('yourapp.Address', on_delete=models.CASCADE)
profile = models.ForeignKey('yourapp.Profile', on_delete=models.CASCADE)
or directly give the class:
address = models.ForeignKey(Address, on_delete=models.CASCADE)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
Both of the other answers were incorrect, I ended up modifying everything and also creating a new model, here it is:
class Address(models.Model):
name = models.CharField(max_length=100, blank=False)
address1 = models.CharField("Address lines 1", max_length=128)
address2 = models.CharField("Address lines 2", max_length=128, blank=True)
city = models.CharField("City", max_length=64)
# state = USStateField("State", default='FL')
state = models.CharField("State", max_length=128, default='FL')
zipcode = models.CharField("Zipcode", max_length=5)
user = models.ForeignKey(Profile, on_delete=models.CASCADE, blank=False)
class Meta:
verbose_name_plural = 'Address'
def __str__(self):
return self.name
I want to reference two foreign keys in the Conversation model, because user_one and user_two can be a Person or Business either way. What is the best way of expressing this?
class Person(models.Model):
"""
Person model
"""
id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
avatar = models.ImageField(upload_to=get_upload_avatar_path, blank=True, null=True, default=None, max_length=255)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
class Business(models.Model):
"""
Business model
` """
id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
name = models.CharField(max_length=255, null=True, default=None)
class Conversation(models.Model):
"""
Conversation model
Contains conversation relational data between registered users
"""
id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
#user_one = models.ForeignKey(Person, null=True, default=None)
#user_two = models.ForeignKey(Business, null=True, default=None)
class ConversationReply(models.Model):
"""
Conversation reply model
Contains conversation reply data
"""
id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
date_time = models.DateTimeField(blank=True, null=True, default=None)
conversation = models.ForeignKey(Conversation, null=True, default=None)
reply = models.CharField(max_length=255)
I would probably use django model inheratance and create an Entity model.
class Entity(models.Model):
id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
class Meta:
abstract = True
class Person(Entity):
"""
Person model
"""
avatar = models.ImageField(upload_to=get_upload_avatar_path, blank=True, null=True, default=None, max_length=255)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
class Business(Entity):
"""
Business model
` """
name = models.CharField(max_length=255, null=True, default=None)
class Conversation(models.Model):
id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
content_object_1 = GenericForeignKey('content_type', 'object_1_id')
content_object_2 = GenericForeignKey('content_type', 'object_2_id')
Note that due to the use of GenericForeignKey filtering will not work the traditional way. Then you'll be able to do something like this:
from django.contrib.contenttypes.models import ContentType
contenttype_obj = ContentType.objects.get_for_model(person_object)
Conversation.objects.filter(object_id_1=person_object.id, content_type=contenttype_obj)