Categories
Python Answers

How to upload multiple images to a blog post in Python Django?

To upload multiple images to a blog post in Python Django, we add a model for the images.

For instance, we write

from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify

class Post(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=128)
    body = models.CharField(max_length=400)
  
def get_image_filename(instance, filename):
    title = instance.post.title
    slug = slugify(title)
    return "post_images/%s-%s" % (slug, filename)  


class Images(models.Model):
    post = models.ForeignKey(Post, default=None)
    image = models.ImageField(upload_to=get_image_filename,
                              verbose_name='Image')

to create the Post and Images models.

And then we reference the post with the image in the Images model.

And we have the image file field.

We use the get_image_filename function to get the image path to save the image file to.

Categories
Python Answers

How to get list of model fields with Python Django?

To get list of model fields with Python Django, we use MyModel._meta.get_fields().

For instance, we write

[f.name for f in MyModel._meta.get_fields()]

to get all the fields with MyModel._meta.get_fields().

Then we get the name of each field with f.name.

Categories
Python Answers

How to perform Python Django database migrations when using Docker-Compose?

To perform Python Django database migrations when using Docker-Compose, we can add the migrate command in a script.

For instance, in docker-entrypoint.sh, we add

python manage.py collectstatic --noinput
python manage.py migrate
python manage.py runserver 0.0.0.0:8000

to collect static files with

python manage.py collectstatic --noinput

We run the database migrations with

python manage.py migrate

And then we start the server with

python manage.py runserver 0.0.0.0:8000

Then we run the script during docker-compose by running the script with a command by putting it in the command property.

Categories
Python Answers

How to filter a Python Django query with a list of values?

To filter a Python Django query with a list of values, we can use the filter method with in.

For instance, we write

Blog.objects.filter(pk__in=[1, 4, 7])

to search Blog entries with pk set to 1,4 or 7 by calling Blog.objects.filter with the pk_in argument set to [1, 4, 7].

Categories
Python Answers

How to fix all records in database have the same value in date field with Python Django?

To fix all records in database have the same value in date field with Python Django, we set the default value to datetime.now or auto_now_add set to True.

For instance, we write

date = models.DateTimeField(auto_now_add=True, blank=True)

or

date = models.DateTimeField(default=datetime.now, blank=True)

to set the created date field to datetime.now() with

default=datetime.now

or

auto_now_add=True