我试图了解如何通过子类化 MultiWidgets 和 MultiValueFields 来创建表单。我有一个简单的地址模型和相关表格:
class Address(models.Model):
user = models.ForeignKey(User)
city = models.CharField(max_length=255)
state = models.CharField(choices = settings.STATES, max_length=50)
postal = models.CharField(max_length=10)
address = models.TextField()
class Meta:
verbose_name_plural = 'Addresses'
class AddressFieldWidget(forms.MultiWidget):
def decompress(self,value):
if value:
return [value[0],value[1],value[2]]
return ''
def format_output(self, rendered_widgets):
str = ''
line_1 = '<td class="align_left"><label for="contact_phone">Address Line 1</label></td>'
for field in rendered_widgets:
str += '<tr>' + line_1
str += '<td class="align_right">%s</td></tr>' % field
return '<tr>' + str + '</tr>'
def value_from_datadict(self,data,files,name):
line_list = [widget.value_from_datadict(data,files,name+'_%s' %i) for i,widget in enumerate(self.widgets)]
try:
return line_list[0] + ' ' + line_list[1] + ' ' + line_list[2]
except:
return ''
class AddressField(forms.MultiValueField):
def __init__(self,*args,**kwargs):
fields = (
forms.CharField(widget=forms.TextInput(attrs={'class':'big'})),
forms.CharField(widget=forms.TextInput(attrs={'class':'big'})),
forms.CharField(widget=forms.TextInput(attrs={'class':'big'})),
)
super(AddressField,self).__init__(*args,**kwargs)
self.widget = AddressFieldWidget(widgets=[fields[0].widget, fields[1].widget, fields[2].widget])
def compress(self, data_list):
return data_list[0] + ' ' + data_list[1] + ' ' + data_list[2]
class AddressFormNew(forms.ModelForm):
postal = forms.CharField(widget=forms.TextInput(attrs={'class':'small'}))
address = AddressField()
city = forms.CharField(widget=forms.TextInput(attrs={'class':'big'}))
class Meta:
model = Address
好吧,在我看来,我无法弄清楚如何使用此表单。我正在尝试做:
@login_required
def render_addresses(request):
address_form = AddressFormNew()
if request.method == 'POST':
address_form = AddressFormNew(request.POST)
if address_form.is_valid():
address_form.save()
return HttpResponse('ok')
else:
return HttpResponse(address_form.errors['address'])
return render_to_response('profile/addresses.html',context_instance=RequestContext(request,{'address_form':address_form}))
结果,Django给了我这个错误:
输入值列表。
此外,当我尝试打印 request.POST.items() 时,它会将地址响应作为 3 个单独的数据提供。
我在这里很迷茫,我必须在一行中获取我的地址数据。我应该如何通过只保存我的表单来实现这一点?
如果有人给我一个明确的解释,我真的很感激。