Reputation: 198
I have to upload a file from django views using the file path from the local system. I'm using models.create method to save the filepath. But the image is not getting uploaded into the media directory.
I have tried the Content and File from django core.utils but it deos not work
def createevent(request):
file_path = os.path.join(settings.FILES_DIR) # Getting the directory with files
f = []
for (dirpath, dirnames, filenames) in walk(file_path):
f.extend(filenames)
break
f.remove(".DS_Store")
img = random.choice(f) # Select a random file
pa = os.path.abspath(img) # absolute file path
# pa = (img,File(pa))
response = File(pa)
print(pa)
loc = "School Ground"
if request.method == 'POST':
get_dateof = request.POST.get('dateof')
get_nameof = request.POST.get('nameof')
get_descof = request.POST.get('descof')
new_report = Event.objects.create(
name=get_nameof,
description=get_descof,
location=loc,
timeoftheevent=get_dateof,
user=request.user,
image= pa
) #creating a db record
return HttpResponse('')
my models.py
class Event(models.Model):
name = models.CharField(max_length=100,blank=False)
description = models.CharField(max_length=100,blank=False)
location = models.CharField(max_length=100,blank=False)
timeoftheevent = models.CharField(max_length=100,blank=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
image = models.FileField(blank=False)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.user.username
Upvotes: 0
Views: 65
Reputation: 788
You can try this.
#This would return a path for your saved images using path name/filename you can always tweak this
def user_directory_path(instance,filename):
return '{0}/{1}'.format(instance.name, filename)
class Event(models.Model):
name = models.CharField(max_length=100,blank=False)
description = models.CharField(max_length=100,blank=False)
location = models.CharField(max_length=100,blank=False)
timeoftheevent = models.CharField(max_length=100,blank=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
image = models.FileField(upload_to = user_directory_path, blank=False)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.user.username
then in your views.py and I'm assuming myfile is the name of the file field in your html form
if request.method == 'POST' and and request.FILES['myfile']:
get_dateof = request.POST.get('dateof')
get_nameof = request.POST.get('nameof')
get_descof = request.POST.get('descof')
myfile = request.FILES['myfile']
#creating a db record............
return HttpResponse('')
you can have a look at this article if it helps
Upvotes: 1