djangodjango-formsdjango-modelsdjango-file-upload

Django: Form field input forgotten/deleted for FileField upon validation


I have the following setup in Django. A text input validated by CharField and a FileField for an image upload. The desired response for when a field is empty should be that the data originally on the form is present and all the user needs to do is fill in the missing data. I've listed the two situations that might require validation and the current state of how the app responds:

How does one hold onto the file data after validation?

view.py

def signin(request, template="signin.html"):

    c['form'] = SignInForm()
    if request.method == 'POST':
        c['form'] = SignInForm(request.POST, request.FILES)

        if c['form'].is_valid():

            #TODO: Commit data
            return redirect("somwhere_else.html")

    return render(request, template, c)

forms.py

class SignInForm(forms.Form):
    name = forms.CharField(max_length=50,required=True)
    photo_input = forms.FileField(required=True)

Solution

  • Here I've found:

    "You can't specify any value in FileUpload control due to security restriction.

    Imagine that you e.g. have such ability, you're specifying file path on the web server and after user has submited the page you are downloading a file which in fact wasnt selected by the user. So, in this case use are stealing file from user computer. Thus, browser limits capabilities of FileUpload control on a client side to just have ability for user to select the file and confirm the upload to a server.

    So that, you should make a file selection the last action the user able to do before any submit.

    Or, use AJAX approach to not submit entire page when selecting smth."