当前位置: 动力学知识库 > 问答 > 编程问答 >

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:

  • The text is present, but the image is forgotten. The result after reload: The text that was originally in the post is still present and all the user has to do is upload the file. This works as desired. Excellent
  • The text is forgotten, but the image is present. The result after reload: The image is no longer present and requires the user to upload it again, which is undesirable.

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)

网友答案:

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."

分享给朋友:
您可能感兴趣的文章:
随机阅读: