Reputation: 13891
I'm trying to upload files for an article model. Since an object can have multiple images, I'm using a foreign-key from file model to my article model. However, I want all the files to have unique titles. Herez the code snippet.
class Article(models.Model):
name = models.CharField(max_length=64)
class Files(models.Model):
title = models.CharField(max_length=64)
file = models.FileField(upload_to="files/%Y/%m/%d/")
article = models.ForeignKey(Article)
Now when I upload the files, I want the file titles to be unique within the "foreign_key" set of Article, and NOT necessarily among all the objects of Files. Is there a way I can automatically set the title of Files? Preferably to some combination of related Article and incremental integers!! I intend to upload the files only from the admin interface, and Files are set Inline in Article admin form.
Upvotes: 2
Views: 1143
Reputation: 4529
def add_file(request, article_id):
if request.method == 'POST':
form = FileForm(request.POST, request.FILES)
if form.is_valid():
file = form.save(commit=False)
article = Article.objects.get(id=article_id)
file.article = article
file.save()
file.title = article.name + ' ' + file.id
file.save()
redirect_to = 'redirect to url'
return HttpResponseRedirect(redirect_to)
Upvotes: 1