I was not sure what to call this question.
I am creating a magazine site using Django 1.10. Using the admin interface, you can add publications. Publications come with several authors who are sorted through through . In addition, you upload PDF files to the publication. I am trying to ensure that PDF files have consistent and reasonable names using the custom upload_to function for FileField as described in the docs . In particular, I want the names to be (lastname of the first author) + "_" + (year of publication) + (a letter that depends on the number of previous publications of the same first author that year) + ".pdf" For example, for the first author of Smith, who publishes the document in 2016, the file name will be Smith_2016a.pdf . The second should be Smith_2016b.pdf , etc. I got this to work when you edit an existing post.
However, if you create a new publication and try to add a PDF, the list index out of range error appears. This is because calling Person.objects.filter(author_of = instance) results in an empty request, because the current object has not yet been saved to the database.
My question is: is it possible to get the last name of the first author of a new publication in some other way? Without this, it is impossible to determine which letter to add per year.
Due to how manytomanyfield works with through , you cannot use instance.authors[0] to get the first author:
(Pdb) instance.authors *** ValueError: "<Publication: Test paper (OQSPS)>" needs to have a value for field "publication" before this many-to-many relationship can be used.
The workaround is to save the publication first without a PDF, then edit it and add the PDF. I tested this and it works.
Perhaps you can force two-stage saving of new publications in the same way that some fields of the new User not edited at the first stage. This seems possible according to a 6 year question .
Some relevant code from models.py :
def custom_filename(instance, filename):
python django
Deleet
source share