Django如何在模板中使用MultiSelectField

2024-05-19 12:25:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在django模板中添加MultiSelectField。我实现了下面的代码,但是模板中有一个问题。然而,在django admin中,它工作得非常好

#models.py

from multiselectfield import MultiSelectField

    class Amenities(models.Model):
        Amenities_Choices =(
            ('Free Wifi','Free Wifi'),
            ('Attach Bathroom', 'Attach Bathroom'),
            ('Shared Bathroom', 'Shared Bathroom'),
            ('Free Laundry Service', 'Free Laundry Service',),
            ('24/7 water facility', '24/7 water facility'),
            ('Geyser', 'Geyser'),
            ('Private TV', 'Private TV'),
        )
        hostel = models.ForeignKey(AddHostel, on_delete=models.CASCADE)
        feature = MultiSelectField(choices=Amenities_Choices)
    
        def __str__(self):
            return self.hostel.location

views.py:

def amenities(request):
    if request.method == "POST":
        hostel = request.POST['hostel']
        feature = request.POST['feature']
        amen = Amenities(hostel_id=hostel, feature=feature)
        amen.save()
    hostels = AddHostel.objects.all()
    return render(request,'staff/amenities.html',{'hostels':hostels})

<div class="col-lg-12"> <form method="post"> {% csrf_token %} <div class="row"> <div class="form-group col-md-6 col-sm-12"> <label for="hostel">Hostel:</label> <select class="form-control form-search-ch" id="hostel" name="hostel"> {% for h in hostels %} <option value="{{ h.id }}">{{ h.hostel_name }}</option> {% endfor %} </select> {# <input type="text" class="form-control form-grp-lbl" id="hostel" name="hostel"#} {# required>#} </div> <div class="form-group col-md-6 col-sm-12"> <!--in this section checkbox is not showing--> {% for value, text in form.amenities.field.choices %} <div class="ui slider checkbox"> <input id="{{ forloop.counter0 }}" name="{{ form.feature }}" type="checkbox" value="{{ feature }}"{% if value in checked_feature %} checked="checked"{% endif %}> <label>{{ text }}</label> </div> {% endfor %} </div> <div class="form-group col-md-12 mx-auto"> <input type="submit" class="form-control" name="register" value="Add" style="width:150px; height: 50px; font-size: 1.2rem; border-radius: 10px 10px;background: #E35452; border: 1px solid rgba(0,0,0,0.5); color: #ffffff"> </div> </div> </form> </div>

Tags: namedivformidfreevaluemodelsrequest
1条回答
网友
1楼 · 发布于 2024-05-19 12:25:58

您可以轻松使用.tag和.choice\u标签

<div class="" style="">
                <p class="col-sm-8"><b>{{form.feature.label}} :</b></p>
            </div>
            <div>
                {% for checkbox in form.diet_goal%}
                <div class="" style="">
                    <span>
                            {{ checkbox.tag }}
                            <label class="" for="{{ checkbox.id_for_label }}">{{ checkbox.choice_label }}</label>
                    </span>

                </div>
                {% endfor %}
            </div>

相关问题 更多 >