私のDjangoアプリケーションでは、モデルのフォームフィールドを手動で表示するテンプレートです。このテンプレートにはいくつかのフィールドがあり、オプションは私のforms.py
に設定されています。オプションの1つはタプル('new','New...')
で、選択するとポップアップウィンドウが表示され(Bootstrap Modal)、ユーザーはselect
の選択肢に追加されたオプションを追加できます。Django:フォームテンプレートの変更時にフォーム属性が失われる<select>
しかし、フォームがsubmitedされている場合、このフィールドの形式キーが欠落しているように、私はエラーを持っている: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
から来る初期オプションの一部ではないことから来ていると思いますか?