我正在尝试实现此示例中给出的步骤(https://github.com/Sidon/djfkf/)来创建一个Django表单,该表单允许基于先前的选择多个值选择。基本上,我有两个模型,一个用于有机体,另一个用于目标。每个生物体可以具有一个或多个目标。我想选择一种生物体,一旦我选择了该生物体,就会出现一个下拉菜单,其中包含所有相关目标。我使用了opt-groups,但没有给我我想要的东西。有人可以帮助。我是网络编程的新手。这只是更大任务的一部分,即开发生物信息学应用程序。看看这个特定目的的代码。
### models ####
from django.db import models
from django.forms import ModelForm
from django.utils.encoding import python_2_unicode_compatible
from django.core.files.storage import FileSystemStorage
import os
from os import path
@python_2_unicode_compatible
class reference(models.Model):
description = models.CharField(max_length=255, blank=True)
file = models.FileField(upload_to='documents/')
def __str__(self):
return self.description
@python_2_unicode_compatible
class target (models.Model):
uploadtargetfs = os.path.join(os.getcwd(), 'targets/')
target_name = models.CharField(max_length=255, default="")
reference_organism = models.ForeignKey(reference, default="")
forward_file = models.FileField(upload_to=uploadtargetfs)
reverse_file = models.FileField(upload_to=uploadtargetfs)
def organism(self):
return self.reference_organism.description
def __str__(self):
return self.target_name
return self.reference_organism
##### forms ####
import json
from django import forms
from django.forms import ModelForm, Textarea
from django_select2.forms import (
HeavySelect2MultipleWidget, HeavySelect2Widget, ModelSelect2MultipleWidget,
ModelSelect2TagWidget, ModelSelect2Widget, Select2MultipleWidget,
Select2Widget
)
from .models import reference, target
class ReferenceForm(forms.ModelForm):
class Meta:
model = reference
fields = ('description', 'file',)
class RegTargetForm(forms.ModelForm):
dvarieties = {}
list_varieties = []
for variety in target.objects.all():
if variety.reference_organism.description in dvarieties:
dvarieties[variety.reference_organism.description].append(variety.target_name)
else:
dvarieties[variety.reference_organism.description] = [variety.target_name]
list_varieties.append((variety.target_name,variety.target_name))
references = [str(reference_organism) for reference_organism in reference.objects.all()]
reference_select = forms.ChoiceField(choices=[(reference_organism, reference_organism) for reference_organism in references])
variety_select = forms.ChoiceField(choices=(list_varieties))
references = json.dumps(references)
varieties = json.dumps(dvarieties)
class Meta:
model = target
fields = ('reference_select', 'variety_select',)
#### views ####
import os
from os import path
from django.conf import settings
from django.http import HttpResponse
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.shortcuts import get_object_or_404
from django.shortcuts import render_to_response
from django.core.urlresolvers import reverse
from django.views.generic.edit import FormView
from django.core.files.base import ContentFile, File
from django.utils.datastructures import MultiValueDictKeyError
from django.core.files.storage import FileSystemStorage
from .models import reference, target
from .forms import ReferenceForm, RegTargetForm
def select_target(request):
targets = target.objects.all()
targets_ids = targets.values_list('id', flat=True)
targets_list = targets.values_list('id').values('reference_organism', 'target_name','forward_file', 'reverse_file')
targets_queryset = targets.values('reference_organism', 'target_name','forward_file', 'reverse_file')
if request.method == 'GET':
variety_form = RegTargetForm(data=request.GET.getlist('target_choice'))
if variety_form.is_valid():
vdata = variety_form.cleaned_data.get
variety_selected = target.objects.filter(target_name=vdata('variety_select'))
var1 = target(reference_organism=variety_selected[0].id, target_name=vdata('target_name'))
var1.save()
else:
return render(request, 'polymorph/select_target.html', {'variety_form':variety_form})
else:
variety_form = RegTargetForm()
return render(request, 'polymorph/home.html', {'variety_form':variety_form})
#### urls ####
from django.contrib import admin
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from . import views
from .views import *
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^home/$', views.home, name='home'),
url(r'^about/$', views.about, name='about'),
url(r'^tutorial/$', views.tutorial, name='tutorial'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^get_reference/$', views.get_reference, name='get_reference'),
url(r'^select_target/$', views.select_target, name='select_target'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
#### select target html ####
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="select-style">
<form action="", method="get">
{% csrf_token %}
{{ variety_form.as_p }}
<p><input type="submit" value="Select"></p>
</form>
</div>
{% endblock %}
{% block js %}
<script language="javascript" type="text/javascript">
//alert('funcionou')
$('#id_variety_select').change(function() {populatetarget(this)});
$('#id_reference_organism').addClass('reference_organism');
varieties = {{ variety_form.varieties | safe }}
references = {{ variety_form.references | safe }};
populatereference();
$('#id_reference_select').empty();
$('#id_reference_select').append('<option value="" disabled selected>First select a reference organism</option>');
function populatereference() {
$('#id_reference_select').empty();
$('#id_reference_select').append('<option value="" disabled selected>Select reference organism</option>');
$.each(references, function(v) {
$('#id_reference_select')
.append($("<option></option>")
.attr("value", references[v])
.text(references[v]));
});
}
function populatetarget(event) {
reference = $("id_reference_select option:selected").text();
$("id_variety_select").empty();
$("id_variety_select").append('<option value="" disabled selected> Select variety</option>')
for (let [v, vvarieties] of Object.entries(varieties)) {
if (v == reference) {
//alert(v);
for (variety in vvarieties) {
$('#id_variety_select')
.append($("<option></option>")
.attr("value", vvarieties[variety])
.text(vvarieties[variety]));
}
}
}
}
</script>
{% endblock %}
请参阅附图,显示我希望它出现的方式
答案 0 :(得分:0)
好的,最后我有时间发布您的测试。
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)
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',)
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})
{% 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 %}
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^register/$', views.register, name='register')
]
{% 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 %}
.
├── 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