新手Django智能/链式菜单麻烦

时间:2013-05-08 19:44:45

标签: python django menu many-to-many chained

我正在尝试制作一个链式选择菜单,我有这个模型:

from django.db import models

class Health_plan(models.Model):
    name = models.CharField(max_length=15)

class Doctors_list(models.Model):
    name = models.CharField(max_length=30)
    specialty = models.CharField(max_length=15)
    health_plans = models.ManyToManyField(Health_plan, related_name="doctors")
    location = models.CharField(max_length=15)

    def __unicode__(self):
        return self.name

这是我的forms.py

class SpecForm(ModelForm):
    a = Doctors_list.objects.values_list('specialty', flat=True)
    unique = [('---------------','---------------')] + [(i,i) for i in set(a)]
    specialty = forms.ChoiceField(choices=unique)
    class Meta:
        model = Doctors_list

class HealthForm(ModelForm):
    hplan = ChainedForeignKey(
        Health_plan, 
        chained_field="specialty",
        chained_model_field="specialty", 
        show_all=False, 
        auto_choose=True
    )  

我的urls.py

from django.conf.urls import patterns, include, url
from testApp.views import spec_form
from testApp.views import health_form 
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    url(r'^$', 'Medbook.views.home', name='home'),
    # url(r'^Medbook/', include('Medbook.foo.urls')),
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^hello/$',  spec_form),
    url(r'^hello/$',  health_form),
)

和我的views.py

from django.shortcuts import render_to_response 
from testApp.forms import SpecForm
from testApp.forms import HealthForm

def spec_form (request):
    if request.method == 'POST':
        form = SpecForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = SpecForm()
     return render_to_response('hello.html', {'form':form})

def health_form (request):
     if request.method == 'POST':
        form = HealthForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = SpecForm()
    return render_to_response('hello.html', {'form':form})

我是Django的新手,我觉得这很棘手。用户必须选择一个专业,然后应该出现涵盖该专业的health_plans。

health_plans与医生有很多关系。当一个人选择专业时,脚本应检查医生是否属于该专业,并检索这些医生持有的所有健康计划。

到目前为止,我在菜单中唯一得到的是:Health_plan object Health_plan object Health_plan object

我希望我说清楚,因为我的代码不是。

任何帮助都很感激

1 个答案:

答案 0 :(得分:2)

这与链式选择无关,这里的大部分代码都无关紧要。问题在于,虽然Doctors_list采用__unicode__方法,但Health_plan却没有。也为该模型定义一个。

(另请注意,模型名称的通常样式是CapWords:DoctorsListHealthPlan。虽然前者实际上仅指单个医生,但它应该只是Doctor。 )