0

I am trying to setup an user-uploaded class through the backend as Django admin. I am trying to make it so the path of the ImageField is based on the user-inputted DateField information; this is what I have.

from django.db import models
from datetime import date

class Article(models.Model):
def img_date(self):
    return str(self.date.year) + str(self.date.month) + str(self.date.day)

#main_title = models.
title = models.TextField(max_length=200)
date = models.DateField()
content = models.TextField()
link = models.CharField(max_length=200)
image = models.ImageField(upload_to=img_date)

However, when I submit the object, I get an error saying "img_date() takes 1 positional argument but 2 were given". I need some help figuring out how to set a manual path like I explained earlier.

Thanks,

wmlk
  • 1
  • 1
  • 2

1 Answers1

0

Have a look at the FileField docs (ImageField inherits from FileField).

In particular, note that the upload_to callable must accept two arguments, the model instance, and the original file name. So your code could look something like this (I removed the date import because it was unused):

from django.db import models

def img_date(instance, filename):
    return str(instance.date.year) + str(instance.date.month) + str(instance.date.day)

class Article(models.Model):
    title = models.TextField(max_length=200)
    date = models.DateField()
    content = models.TextField()
    link = models.CharField(max_length=200)
    image = models.ImageField(upload_to=img_date)

I've used your example code but you'll probably want to modify it so that two articles with the same date don't use the same image path.

Kevin
  • 959
  • 10
  • 14