简体   繁体   English

提交后django清除表单字段

[英]django clear form field after a submit

I have an upload form,After every form submit,i want to clear the posted data,actually the form is holding the submitted data.I know that, this problem can be solved if i redirect my page to some other page,but i don't want to redirect my page,because after submitting data,an success message will show in that page.so how can i clear my form without redirecting my page?我有一个上传表单,每次提交表单后,我想清除发布的数据,实际上表单保存了提交的数据。我知道,如果我将页面重定向到其他页面可以解决这个问题,但我不不想重定向我的页面,因为提交数据后,该页面中会显示一条成功消息。那么如何在不重定向我的页面的情况下清除我的表单?

this is my views.py file这是我的 views.py 文件

def UserImageUpload(request):


    if request.method == 'POST':
            form = DocumentForm(request.POST,request.FILES)
            if form.is_valid():
                    messages.add_message(request, messages.SUCCESS, 'Your Image upload is waiting for Admin approval')


                    newdoc = Photo(photo = request.FILES['photo'],watermarked_image=request.FILES['photo'],user = request.user,name = request.POST['name'],description = request.POST['description'],keyword = request.POST['Image_Keyword'],uploaded_time=datetime.datetime.now(),Certified=request.POST['Certification'])

                    newdoc.save()
            else:
                    messages.add_message(request, messages.ERROR, 'Please Complete All Fields To Submit Your Image')



    else:
            form = DocumentForm()

    uploaded_image = Photo.objects.all()

    return render_to_response('myprofile/user_image_upload.html',{'uploaded_image':uploaded_image,'form':form},context_instance = RequestContext(request))

and this is my forms.py file这是我的 forms.py 文件

from django import forms

class DocumentForm(forms.Form):
    photo = forms.ImageField( 
            label='Select A file',)
    name = forms.CharField(label='Image Name',max_length=50,widget=forms.TextInput(attrs={'class' : 'form-control',}))
    Certification = forms.BooleanField(label='I certify that this is my original work and I am atlest 18 years of age')
    description = forms.CharField(label='Image Description',max_length=500,widget=forms.TextInput(attrs={'class' : 'form-control',}))
    Image_Keyword = forms.CharField(label='Keywords',widget=forms.TextInput(attrs={'class' : 'form-control',}))

While Rego's answer is technically correct, Django best practices dictate that you do a HttpResponseRedirect after a form submission.虽然 Rego 的回答在技术上是正确的,但 Django 最佳实践要求您在提交表单后执行 HttpResponseRedirect。 This reduces the likelihood of accidental multiple submissions.这减少了意外多次提交的可能性。

You have two options for sending data to the redirected page: you could either redirect to a page that indicates the form was submitted successfully, and/or you can use session variables.您有两种将数据发送到重定向页面的选项:您可以重定向到指示表单已成功提交的页面,和/或您可以使用会话变量。

http://docs.djangoproject.com/en/stable/topics/http/sessions/ http://docs.djangoproject.com/en/stable/topics/http/sessions/

Since you can't send your view's local variables to a view that you redirect to, you can save that data in session variables that will be available to any subsequent sessions until it expires or is deleted.由于您无法将视图的局部变量发送到您重定向到的视图,因此您可以将该数据保存在会话变量中,这些数据将可用于任何后续会话,直到它过期或被删除。

For instance, you could put the user's name in a session variable in one view:例如,您可以将用户名放在一个视图中的会话变量中:

# view.py (the one with the form)

request.session['name'] = form.cleaned_data['name']

And then in the view that processes your success notice:然后在处理您的成功通知的视图中:

# view.py (form submission successful)

string = "Hi there, " + request.session['name'] + "!  How are you today?"

This is preferable to not doing a redirect as strongly suggested by the Django gods.这比不进行 Django 众神强烈建议的重定向要好。

I have solved it.In the views.py ,After saving form just assign the empty form , like that我已经解决了。在views.py中,保存表单后只需分配空表单,就像这样

def UserImageUpload(request):

    if request.method == 'POST':
             form = DocumentForm(request.POST,request.FILES)
             if form.is_valid():
                     messages.add_message(request, messages.SUCCESS, 'Your Image upload is waiting for Admin approval')
                     newdoc = Photo(photo = request.FILES['photo'],watermarked_image=request.FILES['photo'],user = request.user,name = request.POST['name'],description = request.POST['description'],keyword = request.POST['Image_Keyword'],uploaded_time=datetime.datetime.now(),Certified=request.POST['Certification'])
                     newdoc.save()
                #Assign the empty form,it will empty the form after a successful form submission
                     form=DocumentForm()  
             else:
                   messages.add_message(request, messages.ERROR, 'Please Complete All Fields To Submit Your Image')
     else:
             form = DocumentForm()
     uploaded_image = Photo.objects.all()
     return render_to_response('myprofile/user_image_upload.html',{'uploaded_image':uploaded_image,'form':form},context_instance = RequestContext(request))

no need to Redirect Your page.无需重定向您的页面。

It is strongly advised to do a redirect after a form submission to prevent accidental duplicate submissions (see Post/Redirect/Get ).强烈建议在表单提交后进行重定向,以防止意外重复提交(请参阅Post/Redirect/Get )。

You can use Django's messages framework to show messages after the redirect.您可以使用 Django 的消息框架在重定向后显示消息。 In your view:在您看来:

from django.contrib import messages
from django.shortcuts import redirect, render
# ...

def UserImageUpload(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            # ... (do something with the submitted form data here) ...
            # The message that will be shown on subsequent displays of the template:
            messages.add_message(request,
                                 messages.SUCCESS,
                                 'Your Image upload is waiting for Admin approval')
            # Redirect back to this view.
            # Attention: Change '...' to the name or URL of this view.
            return redirect('...')
    else:
        form = DocumentForm()

    return render(request, 'myprofile/user_image_upload.html', {
        'form': form,
        'uploaded_image': Photo.objects.all(),
    })

Then, you need to adjust your template (ie myprofile/user_image_upload.html ) to be able to show the message during the next rendering of the template.然后,您需要调整您的模板(即myprofile/user_image_upload.html ),以便能够在模板的下一次呈现期间显示消息。 Add something like this to your template:将这样的内容添加到您的模板中:

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}

Read the reference for more details about displaying messages in your template.有关在模板中显示消息的更多详细信息,请阅读参考资料

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM