首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django:在表单模板中更改<select>选项时释放表单属性

Django:在表单模板中更改<select>选项时释放表单属性
EN

Stack Overflow用户
提问于 2017-11-14 15:36:54
回答 1查看 263关注 0票数 0

在我的Django应用程序中,一个模板,它手动显示来自Model的表单字段。在这个模板中,我有几个字段,这些字段是在我的forms.py中设置的。其中一个选项是元组('new','New...'),当它被选中时会出现一个弹出窗口(Bootstrap ),用户可以添加一个选项,该选项将添加到select的选择中。

但是,当表单被提交时,我有一个错误,因为该字段的表单键缺失:KeyError: 'country',如果打印该表单,则国家键就没有了:

代码语言:javascript
复制
{'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

代码语言:javascript
复制
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

代码语言:javascript
复制
{# 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

代码语言:javascript
复制
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的初始选项的一部分,我如何解决这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-15 11:39:47

如果可以的话,我找到了一种将新的<option>添加到<select> #id_country的方法。在我的forms.py中,我将ChoiceField替换为CharField,其中小部件是放置countryChoicesforms.Select

代码语言:javascript
复制
country = ChoiceField(choices = countryChoices, initial='?', required = False)

通过

代码语言:javascript
复制
country = CharField(max_length=50, widget=forms.Select(choices=countryChoices), required=False)

因此,由于country属性是一个CharField,因此不再存在由invalid_choice引发的验证错误,并且form cleaned_data现在有了键'country'的新值。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47289662

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档