Last active
December 16, 2015 20:29
-
-
Save georgemarshall/5493154 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UploadTestForm(forms.Form): | |
file = forms.FileField() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def generate_filename(instance, filename): | |
""" | |
Generates a folder path that sections files based upon who owns it. | |
""" | |
def get_directory_name(): | |
return os.path.normpath(force_text(force_str( | |
'.files/%s' % instance.owner_id | |
))) | |
def get_filename(): | |
storage = instance.file_path.storage | |
return os.path.normpath(storage.get_valid_name(os.path.basename( | |
filename.lower() | |
))) | |
return os.path.join(get_directory_name(), get_filename()) | |
@python_2_unicode_compatible | |
class File(models.Model): | |
owner = models.ForeignKey(settings.AUTH_USER_MODEL) | |
group = models.ForeignKey('auth.Group', blank=True, null=True) | |
file_path = models.FileField(_('file'), upload_to=generate_filename) | |
file_name = models.CharField(_('file name'), max_length=255) | |
date_created = models.DateTimeField(_('date created'), default=timezone.now) | |
date_modified = models.DateTimeField(_('date modified'), default=timezone.now) | |
class Meta: | |
verbose_name = _('file') | |
verbose_name_plural = _('files') | |
def __str__(self): | |
return self.file_name |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UploadTestView(LoginRequiredMixin, FormView): | |
template_name = 'upload_test.html' | |
form_class = UploadTestForm | |
success_url = reverse_lazy('upload-test') | |
def form_valid(self, form): | |
fp = form.cleaned_data['file'] | |
file, created = File.objects.get_or_create( | |
owner=self.request.user, file_name__iexact=fp.name, | |
defaults={'file_path': fp}) | |
return super(UploadTestView, self).form_valid(form) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment