如何解决使用Django BoundField
嗨,我想从我的视图中将表单单选值作为JSON返回。我不需要html标签,而只需要无线电值的原始数据。
通过用HTML编写{{form.q1.field.choice_label}},我可以得到想要的东西。但我想在视图中获取它,并将其作为json传递给html。
这是我的views.py代码:
def FormBotAPI(request):
form = UserForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
instance = form.save()
for x in form.fields:
data = {
'label_str': form[x].label,'values': str(form[x]),}
return JsonResponse(data,safe=False)
forms.py:
class UserForm(ModelForm):
class Meta:
model = User
fields = '__all__'
models.py:
class User(models.Model):
types1 = (
('destinations','to'),('fields','questions'),('rankings','about'),('Others','human'),)
types2 = (
('destinations','to1'),'questions1'),'about1'),'human1'),)
q1 = models.CharField (
'fieldlabel',help_text='helptext',max_length=200,choices=types1,blank=False,null=True,default='Unspecified'
)
q2 = models.CharField (
'fieldlabel',choices=types2,default='zz'
)
解决方法
我找到了一种方法。我做了研究,没有找到捷径。
简单来说,我通过剥离HTML标签返回了值。我使用了Django本身的带标签快捷方式。
我的views.py:
View row = recyclerView.getLayoutManager().findViewByPosition(0);
EditText editText = (EditText)row.findViewById(R.id.edit_text); //pass the id of your EditText here
editText.setText(str);
已将小部件添加到ModelForm:
import requests
from .models import *
from django.http import JsonResponse
from django.utils.html import strip_tags
def FormBotAPI(request):
form = UserForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
instance = form.save()
context = {
'form': form
}
field = 'q1'
# Delete HTML tags
radio_inputs = [ strip_tags(html_inputs).replace('\n ','') for html_inputs in form[field] ]
# return unique id for each input and label
id_for_label = [ form[field].auto_id + '_' + str(id) for id in range(len(radio_inputs)) ]
# Make a dictionary from two above
choices = [ {'id': id_for_label[i],'label': radio_inputs[i]} for i in range(len(radio_inputs)) ]
data = {
'label': form[field].label,'help_text': form[field].help_text,'choices': choices,}
return JsonResponse(data,safe=False)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。