Issue
I need to store a file path in db using django via ajax form submission .
Here is my view:
def dashboard(request):
container=[]
DIR = os.path.realpath("/home/user/Desktop/Demo")
WAY = os.listdir(DIR)
for file in WAY:
if file.endswith('.mp4'):
file_name = file
FDIR=os.path.join(DIR, file)
container.append(FDIR)
return render(request, 'dashboard.html', {'container': container})
def new_scheduler(request):
if request.method =='POST':
f_name = request.POST.get('file')
dateAndTime = request.POST.get('dateAndTime')
Scheduled_data = schedulesdb.objects.create(
f_name = file,
dateAndTime = dateAndTime,
)
Scheduled_data.save()
return HttpResponse ('done')
It save in database like <type 'file'>
.
Here is my model.py:
class schedulesdb(models.Model):
f_name = models.CharField(max_length=100)
dateAndTime = models.DateTimeField(['%Y-%m-%d %H:%M:%S'],null=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=2)
def __unicode__(self): # on Python 2
return self.f_name
Thanks in advance :)
Solution
From your code it's not 100% clear whether you're intending to handle file uploads from the client, or simply store strings that happen to be a file path (potentially for locating a file on some remote filesystem).
1. File uploads
Consider using the FileField model field type rather than the CharField.
The Django documentation has a solid explanation and examples of how to do simple file uploads.
2. Obtaining the actual POST data value for the f_name field
Your code sample is storing "", because you're assigning 'file' (which is a builtin type) rather than the f_name
variable that you previously declared. Like this:
def new_scheduler(request):
if request.method =='POST':
f_name = request.POST.get('file')
dateAndTime = request.POST.get('dateAndTime')
Scheduled_data = schedulesdb.objects.create(
f_name = f_name, # Note the use of f_name instead of file
dateAndTime = dateAndTime,
)
Scheduled_data.save()
return HttpResponse ('done')
Answered By - Dwight Gunning Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.