提交后如何只清除一个特定的表单字段?

时间:2017-01-06 20:03:16

标签: python django django-forms

我正在创建一个聊天应用程序,有2个字段,接收者的姓名和正文, 我希望在表单提交后清除comment字段的正文而不清除接收者的名字,我该如何实现呢?

views.py

if request.method == 'POST':
    form = userCommentForm(request.POST, request.FILES)
    if form.is_valid():
        form.save(client=request.user)
        > clear comment field.

forms.py (" worker"字段是接收者的名字。)

class userCommentForm(forms.Form):
    worker = CommaSeparatedUserField(label=_(u"worker"), widget=forms.TextInput(attrs={'readonly': 'readonly'}))
    comment = forms.CharField(label=_(u"comment"), widget=forms.Textarea())

    def save(self, client):
        workers = self.cleaned_data['worker']
        comment = self.cleaned_data['comment']
        message_list = []
        for worker in workers:
            msg = userComment(client=client, worker=worker, comment=comment,)

            if None is not None:
                msg.parent_msg = None
                None.save()
            msg.save()
            message_list.append(msg)

        return message_list
        form.save(client=request.user)

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

你在这里有一些误解。在Web应用程序中提交并处理表单后,您不应再继续处理当前请求的任何内容,但是您应该将GET请求发送到另一个网页。因此,提交后无法将表单字段设置为空。

我建议您在提交表单时,重定向到同一页面,但使用GET参数存储提交的名称,然后在视图的开头为表单提供名称为初始参数:

def view_method(request):
    default_receiver = request.GET.get('receiver', None)
    form = userCommentForm(request.POST or None,
                           request.FILES or None,
                           initial={'worker': default_receiver})
    if form.is_valid():
        form.save(client=request.user)
        current_receiver = form.cleaned_data['worker']
        response = redirect('current-page-url-name')
        response['Location'] += '?receiver=%s' % current_receiver
        return response