[英]How can I clear only one specific form field after submit?
I'm creating a chat application and there are 2 fields, receiver's name and body, I would like to clear the body which is the comment
field without clearing the receiver's name after form submit, how can I achieve that ? 我正在创建一个聊天应用程序,其中有两个字段,收件人的姓名和正文,我想清除表单正文,即
comment
字段,而不在提交表单后清除收件人的姓名,我该如何实现?
views.py 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" field is the receiver's name.) form.py (“工作人员”字段是接收方的名称。)
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)
Any suggestions ? 有什么建议么 ?
You have some misunderstanding here. 您在这里有些误会。 After a form is submitted and processed in a web application, you shouldn't continue with anything for current request anymore, but you should send
GET
request to another web page. 在Web应用程序中提交并处理表单后,您不应再继续处理当前请求,而应将
GET
请求发送到另一个网页。 Thus, it's not possible to set a form field as empty after submission. 因此,提交后无法将表单字段设置为空。
What I suggest is that when your form is submitted, you redirect to the same page but with a GET
parameter storing what name was submitted, then in the beginning of the view you feed the form with the name as initial parameter: 我的建议是,提交表单时,您将重定向到同一页面,但是使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.