Skip to content Skip to sidebar Skip to footer

Select Multiple Values From A Previously Selected Dropdown Value In Django Form

I am trying to implement the steps given in this example (https://github.com/Sidon/djfkf/) to create a Django form that allows for multiple selection of values based on a previous

Solution 1:

Ok, finally I have time to post your test.

core/models.py

from django.db import models

class Organism(models.Model):
    name = models.CharField(max_length=20)
    description = models.CharField(max_length=255, blank=True, null=True)

    def __str__(self):
        return self.name

class Target(models.Model):
    name = models.CharField(max_length=20)
    organism = models.ForeignKey(Organism)

    def __str__(self):
        return self.name

class Register(models.Model):
    description = models.CharField(max_length=70)
    organism = models.ForeignKey(Organism)
    target = models.ForeignKey(Target)

core/forms.py

import json
from django import forms
from .models import Organism, Target, Register

class BioForm(forms.ModelForm):

    dtargets = {}
    list_targets = []
    for target in Target.objects.all():
        if target.organism.name in dtargets:
            dtargets[target.organism.name].append(target.name)
        else:
            dtargets[target.organism.name] = [target.name]
        list_targets.append((target.name, target.name))

    organisms = [str(organism) for organism in Organism.objects.all()]

    organism_select = forms.ChoiceField(choices=([(organism, organism) for organism in organisms]))
    target_select = forms.ChoiceField(choices=(list_targets))

    organisms = json.dumps(organisms)
    targets = json.dumps(dtargets)

    class Meta:
        model = Register
        fields = ('organism_select', 'target_select', 'description',)

core/views.py

from django.shortcuts import render
from .forms import BioForm
from .models import Organism, Target, Register

def register(request):
    if request.method == 'POST':
        form = BioForm(data=request.POST)

        if form.is_valid():
            # ... Save your data
            pass
        else:
            # Your implementation
            pass

    else:
        form = BioForm()
    return render(request, 'core/register.html', {'form': form})

core/templates/core/register.html

{% extends "base.html" %}

{% block head %}
{% endblock %}

{% block content %}
    <h1>Registering organism/targets on the Register. <br />(Populate one drop down based on selection in another)</h1>
    <p>Change the contents of drop down Target based on the selection in dropdown Organism, using Django-forms + Javascritp</p>
    <div class="select-style">
        <form action="." method="post">
            {% csrf_token %}
            {{ form.as_p }}
            <p><input type="submit" value="Register a organism/target"></p>
        </form>
    </div>
{% endblock %}

{% block js %}
    {% include "js1.html" %}
{% endblock %}

core/urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^register/$', views.register, name='register')
]

core/templates/js1.html

{% block js %}
    <script language="javascript">

        alert('Load script')

        $('#id_organism_select').change(function() {populateTarget(this)});
        $('#id_description').addClass('descriptions');

        targets = {{form.targets | safe }}
        organisms = {{ form.organisms | safe}};
        populateOrganism();
        $("#id_target_select").empty();
        $("#id_target_select").append('<option value="" disabled selected>First select a brand</option>');


        function populateOrganism() {
            $('#id_organism_select').empty();
            $("#id_organism_select").append('<option value="" disabled selected>Select your option</option>');
            $.each(organisms, function(v) {
                $('#id_organism_select')
                    .append($("<option></option>")
                    .attr("value", organisms[v])
                    .text(organisms[v]));
            });
        }

        function populateTarget(event) {

            organism = $("#id_organism_select option:selected").text();
            $("#id_target_select").empty();
            $("#id_target_select").append('<option value="" disabled selected>Select your option</option>');
            for (let [o, otargets] of Object.entries(targets)) {
                if (o == organism) {
                    for (target in otargets) {
                        $('#id_target_select')
                            .append($("<option></option>")
                                .attr("value", otargets[target])
                                .text(otargets[target]));
                    }
                }
            }
        }
    </script>
{% endblock %}

Project files:

.
├── biotool
│   ├── __init__.py
│   ├── __pycache__
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── core
│   ├── admin.py
│   ├── apps.py
│   ├── forms.py
│   ├── __init__.py
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   ├── __init__.py
│   │   └── __pycache__
│   ├── models.py
│   ├── __pycache__
│   ├── static
│   │   └── css
│   │       └── base.css
│   ├── templates
│   │   ├── base.html
│   │   ├── core
│   │   │   └── register.html
│   │   └── js1.html
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── db.sqlite3
└── manage.py

Screenshot:

Screenshot


Post a Comment for "Select Multiple Values From A Previously Selected Dropdown Value In Django Form"