2016-02-16 107 views
0

我一直在尋找上下,我似乎無法找到正確的答案。Django:填充ModelChoiceField

我一直在使用Django和我的測試項目玩弄,我無法弄清楚如何實現這一點,我想動態基礎上,從我的觀點外鍵顯示下拉內容

這裏是我的樣的觀點:

def job_display(request): 

    job_list = Job_Posting.objects.filter(Publication_Status="A", Available_Slots__gt=0).order_by('-Urgency_Status', '-Date_Modified') 
    context = {'job_list': job_list} 
    return render(request, 'frontend/home.html', context) 

def save_page(request, job_id): 
    jreq = get_object_or_404(Job_Posting, fkey=job_id) 
    form = application_form(request.POST) 
    if request.method == 'POST': 
     ..... 
    else: 
     ..... 
    return render(request, 'frontend/apply.html ...) 

我的網址:

urlpatterns = patterns('', 
    url(r'^$', views.job_display, name='job_display'), 
    url(r'^(?P<job_id>[0-9]+)/apply$', views.save_page, name='save_page'), 
) 

我320交織:

class edbackgound(ModelForm): 
    COURSE = forms.ModelChoiceField(queryset=Educational_Requirement.objects.all()) 

我的模型:

class Course_Selection(models.Model): 
    Course = models.CharField(max_length=30, unique=True) 
    Abbreviation = models.CharField(max_length=100, unique=True) 

class Job(models.Model): 
    Job_Position = models.CharField(max_length=30, null=True, unique=True) 

class Job_Posting(models.Model): 
    fkey = models.OneToOneField(Job, verbose_name="Job Positions") 
    .... 

class Educational_Requirement(models.Model): 
    fkey = models.OneToOneField(Job_Posting, verbose_name="Job Positions") 
    Ed_req = models.OneToOneField(Course_Selection, verbose_name = 'Educational Requirement') 

    def __unicode__(self): 
     return self.Ed_req 

我的問題是顯示中的ModelForm的選擇,在我的意見,我可以得到當前通過jreq.fkey選擇job_list通過save_pagejreq在那裏我可以只得到它的Job_position然後保存我的形式。如何通過我選擇的job_list填充我的表單的ModelChoiceField

如果我的職位是不明確的,請隨意評論什麼我的帖子沒有

編輯 我發現,你可以通過視圖像這樣設置你的queryset

form.fields['COURSE'].queryset = Educational_Requirement.objects.filter(fkey=jreq.fkey_id)

我的那個問題是我使用的是inlineformset_factory動態生成我的領域,如果我這樣做:

for form in myinlineform: 
    form.fields['COURSE'].queryset = Educational_Requirement.objects.filter(fkey=jreq.fkey_id)` 

我養了一個錯誤,指出:[u'ManagementForm data is missing or has been tampered with']

回答