views:

30

answers:

1

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.

A: 
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)      
Seitaridis
Nice approach. But I was trying to set the "title" of the file, rather than filename itself. Is there a way to make the file title dependent on the foreignkey article's name?
Neo
@Neo - you'd have to be careful, since multiple Files could belong to the same Article.
Dominic Rodger
Exactly, thats why the title should be based on Article-Name + Some Integer. I realize it will take some tweaking in Django, since Inline objects are created first, and then their foreginkey is set after the main object is created. Is there a work-around?
Neo
What is the difference between "file" field and "title" field? Does title represents the name of the file?
Seitaridis
while displaying an Article object, I wanted to show the file contents in a textbox, and use the title for the textbox's title. Ofcourse, if a user provides his/her own title, then the "automatically generated" title should be overridden.
Neo
Can you can display the title as a combination formed from the id of the File object and the Article's name field? This is a unique combination.
Seitaridis
Yea, that will work. But how can I automatically set the title upon saving File Object?
Neo
Test to see if my updated answer works.
Seitaridis
Hmm, obviously I need to tweak it a bit more. But yes, it will work. Thanks.
Neo