get file name from request.files

I have a model and a form to upload an image and save it in storage and db. I am able to save to storage but i can’t save it to db because i need the name of the file. How to get the name of the file?

i am using the form:

	{% csrf_token %}
	{{ form.as_p }}

here is what i am trying to save:

form = DocumentForm(request.POST, request.FILES)
    if form.is_valid():

    #item_list2 = Order.objects.filter(id =
    #for order in item_list2:
    #order.image = "https://cfename.ap-south-1...../filename" (get the file name)
    #order.payment_date =
    #order.pay_confirm = False


If you’re creating a form with a FileField, then you don’t need to worry about that. See the docs at File Uploads | Django documentation | Django, along with the API at Uploaded Files and Upload Handlers | Django documentation | Django.

here is my modle:

image = models.ImageField(upload_to='receipts/',null=True, blank=True)

here is my form:

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = ('image', )

and this is the html:

<form action="#" method="POST" enctype="multipart/form-data">
	{% csrf_token %}
	{{ form.as_p }}
	<input type="submit" value="submit" class="btn btn-secondary">

should i change the imagefield to filefield?

An ImageField is a FileField. See Model field reference | Django documentation | Django

then how to save to db using my given code above? how to reference the name to the db?

What is it you’re trying to save? If the FileField is a field in the model, it will be saved in the DB.

here is the problem, i need to have the filepath and i am using linode storage.

the file b.png is not saved when i do the but the file is saved in the storage.
the file is saved but not saved in the DB and i am not sure why?

Are you saying you want the actual data from the file stored in the database?

(As a general rule, that’s really a suboptimal solution. See the Note at Model field reference | Django documentation | Django)

But if you really want to do that, you then need to take the file data and save it as an appropriate field in the database.

that is my question, how to get the file name chosen before uploading?

You can’t. That information isn’t available to you before they (the user) clicks submit.

yes sure so after submit (i have one) then if the action is post i will do something:

in i have

if request.method=='POST':

then i can get the name of the file, correct? I am already saving some info after submit:

item_list2 = Order.objects.filter(id =
for order in item_list2:
    #order.image = ""
    order.payment_date =
    order.pay_confirm = False

so i only need to get the name of the file.

What is your ultimate objective here? What is it that you’re really trying to accomplish? (Or, to phrase it another way, what do you want to have happen with an uploaded file?)

The name of the file referenced by a FileField is available through the api referenced by one of the earlier links I provided. But at this point, I’m not understanding what the real question is.

i am saving the receipt in the storage and i need to keep record of the name so that when user goes to order history he can see the payment he did (uploaded photo of payment) if he paid by bank transfer. that image i am uploading is part of the order model

class Order(models.Model):
	customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
	date_ordered = models.DateTimeField(auto_now_add=True)
	payment_date = models.DateTimeField(blank=True, null=True)
	complete = models.BooleanField(default=False,null=True,blank=False)
	transaction_id = models.CharField(max_length=200, null=True)
	image = models.ImageField(upload_to='receipts/',null=True, blank=True)
	pay_confirm = models.BooleanField(default=False,null=True,blank=False)

The original file name is irrelevant. The file may actually end up stored under a different physical name on the server.

However, a FileField has an api allowing you to access all the information the system maintains for that file. See Model field reference | Django documentation | Django

1 Like

Thank you very much you are a life saver.

Hi ! I’m facing a similar problem , when I try to login from the form that i created in react.js and connected it with django i face error (User matching query does not exist.) and I’m sure that i used an email and password that exist in the database.

I think the problem here but i couldn’t solve it for days
could you help me please ?

from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.views import APIView
from rest_framework import generics
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from .serializers import UserSerializer
from .models import User

class UserList(generics.ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    #permission_classes = [IsAuthenticated]

class UserDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer 
    #permission_classes = [IsAuthenticated] 

def user_login(request):
    email = request.POST['email']
    password = request.POST['password']
    formValues = User.objects.get(email= email, password= password)

    if formValues:
        return JsonResponse ({'bool':True  #, 'user_id'
        return JsonResponse ({'bool':False})

Image from iOS

I suggest you open a new topic for this discussion. This topic has been marked as solved.

When you do, in addition to posting this code there, please post the text of the error message (the full traceback) from the console window where you’re running runserver (or runserver_plus) and not just a screen image of the browser error display.

I added it