[Django]-Based on model multiselectfield show result in template django

0👍

acc to me there is no such way by which u can show the result base on selected option because i also tried to use that and look for answers on internet but didn’t find anything and creator of that repo is also not responding although I would recommend you to use models many to many field It will allow user to select more than one option like multiselectfield like this

first, create models

class Lunch(models.Model):
    title = models.CharField(max_length=200)

    def __str__(self):
        return self.title

then add this in student models

lunch =  models.ManyToManyField(Lunch, blank=True, related_name="lunch")

then add your option in lunch model

and it in your template to show result base on selected option

{% if student.classs %}
{% for Lunch in student.lunch.all %}
{% if Lunch.title == 'Sandwich' %}
          <p> your sandwich will be ready</p>
{% endif %}
{% endfor %} 
{%endif%}

it will work

3👍

OP can create a model for lunches (it would enable to create new lunches, edit and delete). Then, in the Student model create a lunch with a ManyToManyField, like

lunch = models.ManyToManyField(Lunch, blank=True)

Note the usage of blank=True to not require the field in the forms.

Then, when one generates a form based on that model, it’ll create an experience just like the one in Django Admin where one can select multiple ones.

One can then show it to the user in a template.


If one doesn’t like the experience of the form and want to make it more user friendly, there are some articles out there explaining that

0👍

This happens because the string is being compared to type: type(aaa[0].lunch) <class ‘multiselectfield.db.fields.MSFList’>. Printed the data type ‘type(aaa[0].lunch)’ of the first value from the database in the view. Used stringformat:’s’ to convert data to string in template. Here you can read about the conversion:
conversion

transformation type:

replace ‘samplesite’ with the name of your application.

urls.py

urlpatterns = [
   path("Test/", Test, name = 'Test'),
]

views.py

def Test(request):
    aaa = student.objects.all()
    print('type(aaa[0].lunch)', type(aaa[0].lunch))
    context = {'fff': aaa}

    return render(request, 'samplesite/lunch.html', context)

lunch.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
</head>
<body>
    {% for aa in fff %}
    {% if  aa.lunch|stringformat:'s' == 'Sandwich' %}
    <p>{{aa.lunch}}</p>
    <p>{{aa.name}}</p>
    {% endif %}
    {% endfor %}
</body>
</html>

settings in settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }

django version 4.1
enter image description here

Leave a comment