2

I am making an app where users can upload files to an AWS S3 Bucket. Each user, when signing up, gets a folder within the media folder based on their userID How to I allow my users to upload their projects to that their folders? The files upload just fine, but to a folder named None. This seems like an easy answer, but I cannot seem to find it. Here's my views.py

def new(request):
    title = "Add New Project"
    if not request.user.is_authenticated():
        raise Http404
    form = ProjectForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.fileLocation = request.user.id
        instance.user = request.user
        instance.save()
        return redirect("/dashboard/")
    context = {
        "form": form,
        "title": title,
    }

Here's my models.py

from django.db import models
from django.conf import settings

# Create your models here.
class Project(models.Model):
    fileLocation = None
    user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True)
    title = models.CharField(max_length=200)
    description = models.TextField()
    sell = models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now_add=True)
    image = models.FileField(upload_to=fileLocation, null=True, blank=True)
    def __str__(self):
        return self.title

And here's my forms.py (just in case)

from django import forms
from .models import Project
from django.contrib.auth.models import User

class ProjectForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ProjectForm, self).__init__(*args, **kwargs)
        self.fields['image'].required = True

    class Meta:
        model = Project
        fields = [
            'title',
            'description',
            'image',
            'sell',
        ]
pepper5319
  • 667
  • 4
  • 8
  • 24

2 Answers2

0

Send the request param to your modelForm init .. and use that (assuming you will then have access to request.user) to set the location field specific to that user

Bobby Chowdhury
  • 334
  • 1
  • 7
  • Could you please be a bit more specific – pepper5319 May 21 '16 at 22:54
  • sorry I wasn't that detailed, but this question has already been answered in several different ways. Can you check this link for a duplicate issue: [link](http://stackoverflow.com/questions/5135556/dynamic-file-path-in-django). Also you may want to use ImageField directly instead of FileField to have a better handle over image dimension, filetype checks, etc. – Bobby Chowdhury May 22 '16 at 00:05
0

The issue is in your models.py.

Add this:

def fileLocation(instance, filename):
  return 'uploads/{0}/{1}'.format(instance.owner.username, os.path.basename(filename))

remove this:

fileLocation = None

and your user's file should go into uploads/<username>/<filename>.

As BobbyC mentioned, you should use ImageField instead of FileField

Jeremy S.
  • 1,086
  • 8
  • 18