我在一个简单的问题上敲了两天,我相信了!
简单模型:
class CryptoOptions(models.Model):
setting_name=models.CharField(max_length=100)
dictionary=models.TextField()
alphabet=models.TextField()
criteria_types = (('ASCII', 'ASCII set'),
('EN', 'English language'),
('CUSTOM', 'Custom criteria'),
)
criteria=models.CharField(max_length = 32, choices=criteria_types, default='ASCII')
operation_types = (('xor', 'XOR'),
('ror', 'Rotation Right'),
('rol', 'Rotation Left'),
('shiftl', 'Shift Left'),
('shiftr', 'Shift Right'),
('rot13', 'Rotation 13'),
('base64', 'Base 64')
)
operation = models.CharField(max_length = 32, choices=operation_types, default='xor')
def __unicode__(self):
return u'%s' % (self.setting_name)
Simple ModelForm:
class CryptoOptionsForm(ModelForm):
optionid= forms.ModelChoiceField(queryset=CryptoOptions.objects.all(),initial=0)
class Meta:
model = CryptoOptions
fields = ['dictionary', 'alphabet', 'criteria','operation']
在视图中:
xoratorForm=None
if request.method == 'POST':
if 'optionid' in request.POST:
if request.POST['optionid'].isdigit():
defaultOption=CryptoOptions.objects.get(pk=int(request.POST['optionid' ]))
xoratorForm=CryptoOptionsForm(instance=defaultOption)
xoratorForm.fields['optionid'].initial=int(request.POST['optionid'])
if xoratorForm.is_valid():
print "Valid"
print xoratorForm.cleand_data
else:
print "Errors"
print xoratorForm.errors
request.POST已完全填满:
<QueryDict: {u'dictionary': [u'Windows\r\nCopyright\r\nSystem32'], u'alphabet': [u'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'], u'optionid': [u'1'], u'criteria': [u'ASCII'], u'csrfmiddlewaretoken': [u'QsSHIMhYgANR0a5a1FJ9gCLey5DcAINp'], u'operation': [u'xor']}>
DjangoForm似乎也充满了价值观。
我不知道这里发生了什么,有什么方法可以调试吗?
另一种方式有效:
defaultOption=CryptoOptions.objects.get(pk=int(request.POST['optionid' ]))
print defaultOption
#xoratorForm=CryptoOptionsForm(instance=defaultOption)
#xoratorForm.fields['optionid'].initial=int(request.POST['optionid'])
xoratorForm=CryptoOptionsForm(request.POST,instance=defaultOption)
但这不是我的预期目的,因为我想从defaultOption而不是提交的表单更改表单。 它可能不喜欢我传递Meta对象而不是整个对象包括多选字段的事实?
我是Django新手!
今天的最后一次发现是试图以这种方式覆盖这些方法:
class CryptoOptionsForm(ModelForm):
optionid= forms.ModelChoiceField(queryset=CryptoOptions.objects.all(),initial=0)
class Meta:
model = CryptoOptions
fields = ['dictionary', 'alphabet', 'criteria','operation']
def __init__(self, *args, **kwargs):
if kwargs.get('instance'):
print "Instance INIT"
if isinstance(kwargs['instance'],CryptoOptions):
object = kwargs['instance']
kwargs.setdefault('initial', {})['optionid'] = object.pk
kwargs.setdefault('initial', {})['model'] = object
else:
print "POST INIT"
print kwargs
return super(CryptoOptionsForm, self).__init__(*args, **kwargs)
但是表格再次无法验证。 不确定我做错了什么!