在我的Django应用程序中,一个模板,它手动显示来自Model的表单字段。在这个模板中,我有几个字段,这些字段是在我的forms.py中设置的。其中一个选项是元组('new','New...'),当它被选中时会出现一个弹出窗口(Bootstrap ),用户可以添加一个选项,该选项将添加到select的选择中。
但是,当表单被提交时,我有一个错误,因为该字段的表单键缺失:KeyError: 'country',如果打印该表单,则国家键就没有了:
{'genotype': '?', 'complete_genome': False, 'seq_tech': '?', 'isolation_source': 'te', 'mol_type': '?', 'NT_seq': 'TTG', 'source': '?', 'host': 'chicken', 'species': 'A', 'isolate': 'te1', 'sourceLink': '', 'subtyping_ref': '?', 'PK_idSequence': 'test', 'strain': 'te1_strain', 'comment': '', 'subtype': '?'}我的forms.py
UNKNOWN_START_LIST = [('?','?')]
NEW_END_LIST = [('new','New...')]
class SequenceForm(ModelForm):
# create the form fields
PK_idSequence = CharField(max_length=15, label='Sequence ID')
# get the existing country values in the database
tmpCountries = sorted(list(set([seq.country for seq in Sequence.objects.all() if seq.country is not None and seq.country != '?'])))
countryChoices = UNKNOWN_START_LIST + [(tmpCountry, tmpCountry) for tmpCountry in tmpCountries] + NEW_END_LIST
# the countryChoices will be [('?', '?'), ('France', 'France'), ('Germany', 'Germany'), ('Japan', 'Japan'), ('USA', 'USA'), ('new', 'New...')]
country = ChoiceField(choices = countryChoices,
initial='?',
required = False)
# ... more stuffs
class Meta:
model = Sequence
fields = ['PK_idSequence', 'genotype', 'subtype', 'host', 'country', 'complete_genome', 'seq_tech', 'NT_seq', 'col_date',
'isolation_source', 'isolate', 'strain', 'species', 'mol_type', 'subtyping_ref', 'source', 'sourceLink', 'comment']
# custom clean form for Sequence
def clean(self):
cleaned_data = super(SequenceForm, self).clean()
# where the error is raised
if cleaned_data['country'] is not None:
cleaned_data['country'] = cleaned_data.get('country').title()我的template.html
{# The modal window to record a new Country #}
<div id="modal_new_country" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Record a new country:</h5>
</div>
<div class="modal-body">
<input type="text" name="new_country_text" id="new_country_text">
</div>
<div class="modal-footer">
<button id="new_country_button" type="button" class="btn btn-primary">Submit</button>
<button id="new_country_cancel_button" type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<form class="single_upload_form" action="{% url 'upload' dataType method %}" method="post">
{% csrf_token %}
<div class="container">
<div class="row">
<div class="col">
<div class="{{form.name.css_classes}}">
{{form.PK_idSequence.label_tag}}{{ form.PK_idSequence.errors }}</br><span class="form_field">{{ form.PK_idSequence }}</span>
</div>
</div>
<div class="col">
<div class="{{form.name.css_classes}}">
{{ form.country.label_tag }}{{ form.country.errors }}</br><span class="form_field">{{ form.country }}</span>
</div>
</div>
<div class="row">
<div class="col">
<input type="submit" value="Submit"/>
</div>
</div>
</form>我的jQuery.js
jQuery(document).ready(function() {
/* ############### Country dropdown select ############### */
// in upload form if Country dropdown is set to New... create a modal to get the new country
$("#id_country").change(function(){
var selectedValue = $(this).find("option:selected").attr("value");
switch (selectedValue){
case "new":
$('#modal_new_country').modal('show');
break;
}
});
// Add the new Country to the select options
$("#new_country_button").click(function() {
var newCountry = $("#new_country_text").val();
newCountry = newCountry.substr(0,1).toUpperCase() + newCountry.substr(1);
$('#id_country').append('<option value="'+newCountry+'" selected="selected">'+newCountry+'</option>');
$('#modal_new_country').modal('hide');
});
// cancel button for modal Country set selected option to '?'
$("#new_country_cancel_button").click(function() {
$('#id_country').val('?');
$('#modal_new_country').modal('hide');
});
})我想问题来自于select id_country中的新值不是来自form的初始选项的一部分,我如何解决这个问题?
发布于 2017-11-15 11:39:47
如果可以的话,我找到了一种将新的<option>添加到<select> #id_country的方法。在我的forms.py中,我将ChoiceField替换为CharField,其中小部件是放置countryChoices的forms.Select
country = ChoiceField(choices = countryChoices, initial='?', required = False)通过
country = CharField(max_length=50, widget=forms.Select(choices=countryChoices), required=False)因此,由于country属性是一个CharField,因此不再存在由invalid_choice引发的验证错误,并且form cleaned_data现在有了键'country'的新值。
https://stackoverflow.com/questions/47289662
复制相似问题