Reputation: 2373
I'm trying to upload files using Django-filetransfer and I was wondering how to import the username to use as the name of the file the uploads are saved in. Right now I'm using User.username, but that is invalid. I guess the big question is how to access a user's attributes from models.py. Below is my models.py:
from django.db import models
from django.contrib.auth.models import User, UserManager
class UploadModel(User,models.Model):
title = models.CharField(max_length=64, blank=True)
user = models.ForeignKey(User)
file = models.FileField(upload_to='./uploads/'+str(User.username))
@property
def filename(self):
return self.file.name.rsplit('/', 1)[-1]
UPDATED: app/upload/models.py
from django.db import models
from django.contrib.auth.models import User, UserManager
def uploadmodel_file_upload_to(instance, filename):
return 'uploads/%s/%s' % (instance.user.username, filename)
class UploadModel(models.Model):
user = models.ForeignKey('auth.user')
file = models.FileField(upload_to=uploadmodel_file_upload_to)
TemplateSyntaxError at /upload Caught DatabaseError while rendering: column upload_uploadmodel.user_id does not exist LINE 1: SELECT "upload_uploadmodel"."id", "upload_uploadmodel"."user...
Upvotes: 0
Views: 446
Reputation: 33420
Model attributes are officially defined when Python parses models.py code. You should use a callback for upload_to, to be generate the upload file path using the user related instance, for example:
def uploadmodel_file_upload_to(instance, filename):
return 'uploads/%s/%s' % (instance.user.username, filename)
class UploadModel(models.Model):
user = models.ForeignKey('auth.user')
file = models.FileField(upload_to=uploadmodel_file_upload_to)
Upvotes: 3