Django在提交后清除表单字段

vptzau2j  于 2023-10-21  发布在  Go
关注(0)|答案(3)|浏览(181)

我有一个上传表单,每次提交表单后,我都想清除已发布的数据,实际上表单中保存着已提交的数据。我知道,如果我将页面重定向到其他页面,这个问题就可以解决,但我不想重定向我的页面,因为提交数据后,page.so中会显示一条成功消息,我如何才能在不重定向页面的情况下清除表单?
这是我的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',}))
rkkpypqq

rkkpypqq1#

在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))

无需重定向您的页面。

fdbelqdn

fdbelqdn2#

虽然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神强烈建议的不做重定向更好。

camsedfj

camsedfj3#

    • 强烈建议**在表单提交后进行重定向,以防止意外的重复提交(参见Post/Redirect/Get)。

您可以使用Django的messages framework来显示重定向后的消息。在你看来:

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 %}

有关在模板中显示消息的更多详细信息,请阅读参考资料。

相关问题