I'm trying to learn django, and this has me at the end of my rope. I'm using requests to try and post a user-uploaded image file to an external site, following this example. For testing purposes, I'm using request bin for the url so I can see what's being posted.
When I hardcode a filepath and name into files to test, the whole thing works great. My problem is I don't understand what to do to handle the real-world use case, where I don't know what the user's named the file, and the path will change based on date/month/year.
Every post I've seen on this, as well as the requests example, looks like this:
>>> files = {'file': open('report.xls', 'rb')}
models.py
def get_image_path(instance, filename):
return '/'.join(['help_screens/%Y/%m/%d', filename])
class Help(Timestamp):
First_name = models.CharField(max_length=30)
Last_name = models.CharField(max_length=40)
email = models.EmailField()
themessage = models.TextField()
screenshot = models.ImageField(
upload_to=get_image_path,
null=True,
blank=True
)
views.py
def help_form(request):
form = HelpForm()
if request.method == 'POST':
form = HelpForm( request.POST, request.FILES )
if form.is_valid():
First_name = form.cleaned_data['First_name']
Last_name = form.cleaned_data['Last_name']
email = form.cleaned_data['email']
themessage = form.cleaned_data['themessage']
screenshot = form.cleaned_data['screenshot']
# Email the help request
template = get_template('help_template.txt')
context = Context({
'First_name': First_name,
'Last_name': Last_name,
'email': email,
'themessage': themessage,
'screenshot': screenshot,
})
content = template.render(context)
mail = EmailMessage(
'New help request',
content,
'test website <test@test.com>',
['my.test@mytest.com', email],
headers = {'Reply-To': email }
)
if screenshot:
mail.attach(screenshot.name, screenshot.read())
mail.send()
# End email the help request
form = form.save(commit=False)
url = 'http://requestb.in/xxxxxx'
payload = {
'First_name': First_name,
'Last_name': Last_name,
'email': email,
'themessage': themessage,
}
if screenshot != None:
# this works, but it's a test to a hard-coded file. the
# problem remains, how to get the filepath and file.
# files = {'screenshot': open('test/media-root/help_screens/boots.jpg', 'rb')}
files = {'screenshot': open('screenshot.jpg', 'rb')}
req = requests.post(url, data=payload, files=files)
else:
req = requests.post(url, data=payload)
req.text
form.save()
return render(request, 'help/thanks.html')
return render(request, 'help/help.html', {
'form': form,
})