简体   繁体   中英

Add editable choices in django

I am trying to add a editable choicefield in django like the picture, already do some research on this. Unfortunately, the solution like django-autocomplete doesn't quite fulfill my needs. The autocomplete looks fine, but if do so, I need create a django modal to generate the choices through a url view request, but in my case, it doesn't necessary to do that, I just need put these 3 choices for ip address in the dropdown list, and choose one of them then edit it or submit.

The solutions I found, but they are not very well fit my need:

Django admin: Change selected box of related fields to autocomplete

Django editable dropdown field

在此输入图像描述

If you want to use just those three entries the quickest way is to use a datalist , it just needs to be added into your HTML somewhere.

 <div id="page-wrapper"> <label for="ip">Network address</label> <input type="text" id="ip" list="ip-datalist"> <datalist id="ip-datalist"> <option>192.168.0.0/24</option> <option>10.0.0.0/24</option> <option>172.16.0.0/24</option> </datalist> </div> 

If your options are likely to never change, you could hardcode them into your html like the answer above. If you're generating your dropdown using a form however it would be better to do something like this:

class MyForm(forms.Form):

    ip_list = ((1, '192.168.0.0/24'), (2, '10.0.0.0/24'),
        (3, '172.16.0.0/24'), )

    network_address = forms.ChoiceField(label='Network Address',
        choices=ip_list)
    ...

Once you render the form object in your template it ends up producing html like this:

<label for="id_network_address">Network Address:</label>
<select id="id_network_address" name="network_address">
    <option value="1">192.168.0.0/24</option>
    <option value="2">10.0.0.0/24</option>
    <option value="3">172.16.0.0/24</option>
</select>

This way it is easier to change the ip_list in future if you need to, plus its keeps all your code in one place. This is explained in the docs here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM