Django 提交后清空表单字段
我有一个上传表单,每次提交表单后,我想清空已提交的数据。实际上,表单会保留提交的数据。我知道,如果把页面重定向到其他页面,这个问题可以解决,但我不想重定向页面,因为在提交数据后,页面上会显示一个成功的消息。那么,我该如何在不重定向页面的情况下清空我的表单呢?
这是我的 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))
这是我的 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',}))
3 个回答
在提交表单后强烈建议进行重定向,这样可以防止用户不小心重复提交表单(详细信息可以查看Post/Redirect/Get)。
你可以使用Django的消息框架在重定向后显示消息。在你的视图中:
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(),
})
接着,你需要调整你的模板(也就是myprofile/user_image_upload.html
),以便在下次渲染模板时能够显示消息。可以在模板中添加类似这样的内容:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
想了解更多关于如何在模板中显示消息的细节,可以查看参考文档。
虽然Rego的回答在技术上是正确的,但根据Django的最佳实践,提交表单后应该进行HttpResponseRedirect。这可以减少意外重复提交的可能性。
你有两种方法可以将数据发送到重定向后的页面:你可以重定向到一个显示表单提交成功的页面,或者使用会话变量。
http://docs.djangoproject.com/en/stable/topics/http/sessions/
因为你不能将视图中的局部变量直接发送到你重定向到的视图,所以你可以把这些数据保存在会话变量中,这样在会话过期或被删除之前,任何后续的会话都可以使用这些数据。
例如,你可以在一个视图中把用户的名字放到一个会话变量里:
# view.py (the one with the form)
request.session['name'] = form.cleaned_data['name']
然后在处理成功通知的视图中使用这个变量:
# view.py (form submission successful)
string = "Hi there, " + request.session['name'] + "! How are you today?"
这样做比不进行重定向要好,这也是Django的开发者们强烈建议的做法。
在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))
不需要重新加载你的页面。