A
A
albertalexandrov2018-04-09 20:12:29
Django
albertalexandrov, 2018-04-09 20:12:29

Function for upload_to?

Hello!
There are two clarifying questions on the following code ( source ):

from django.conf import settings
from django.db import models

def upload_update_image(instance, filename):
    return "updates/{user}/{filename}".format(user=instance.user, filename=filename)

class Update(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    content  = models.TextField(blank=True, null=True)
    image = models.ImageField(upload_to=upload_update_image, blank=True, null=True)
    updated = models.DateTimeField(auto_now=True)
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.content or ""

1. Why is the construction used user = models.ForeignKey(settings.AUTH_USER_MODEL), and not, for example, user = models.ForeignKey(USER)?
2. If we write to upload_to=something that is not equal to a string or a variable that stores a string, is this automatically perceived by django as a function with default variables?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-04-09
@albertalexandrov

  1. Because if it is simple to register User, the code will not work in those projects where the user model is overridden.
  2. On the contrary, if something that cannot be called is passed to upload_to, then this is a string.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question