2012-09-28 76 views
3

我的模型是什麼樣子.....外鍵關聯的形式保存在Django

Student(models.Model): 
    name = models.CharField(max_length = 60, blank = False) 
    r_no = models.CharField(max_length = 60, blank = False) 
    created_date = models.DateTimeField(null = False, blank = False, default = datetime.datetime.now()) 

StudentPotential(models.Model): 
    aka_name = models.CharField(max_length = 60, blank = True) 
    ----- 
    ----- 
StudentCorrespondence(models.Model): 
    student = models.ForeignKey('Student', related_name = "Student_FK") 
    student_p = models.ForeignKey('Student', related_name = "Student_FK") 
    emailed_date = models.DateTimeField(null = True, blank = True) 
    phoned_date = models.DateTimeField(null = True, blank = True) 

我在form.py

class StudentPotentialForm (forms.ModelForm): 

    class Meta: 
     model = StudentPotential 

class StudentCorrespondenceForm(forms.ModelForm): 
    class Meta: 
     model = StudentCorrespondence 
     exclude = ('student', 'student_p') 

最後我view.py形式

def add_student_company_potential(request, student_id): 
    from cdradmin.forms import StudentPotentialForm, StudentCorrespondenceForm 
    if request.method == 'POST': 
      ### HOW TO SAVE THE two from for the student have its it 'student_id' #### 

    else: 

      StudentPotentialForm = StudentPotentialForm() 
      StudentCorrespondenceForm = StudentCorrespondenceForm() 
context = {'StudentCorrespondenceForm':StudentCorrespondenceForm, "StudentPotentialForm":StudentPotentialForm} 
return render_to_response('cdradmin/studentform.html', context, context_instance = RequestContext(request)) 

一旦數據發佈到視圖中,我如何能夠爲學生保存此數據,他/她的ID是'student_id'

回答

3

你可以試試這個

if request.method == 'POST': 
    spf = StudentPotentialForm(request.POST) 
    if spf.is_valid(): 
     osp = spf.save() 
    else : 
     #raise error 

    student = Student.objects.get(id=student_id) 
    scf = StudentCorrespondenceForm(request.POST) 
    if scf.is_valid(): 
     osc = scf.save(commit=False) 
     osc.student = student 
     osc.student_p = osp 
     osc.save() 
    else: 
     # raise error. 
+0

spf.is_valid()總是False.this模型沒有任何特殊的領域。 –

+0

如何在控制檯中打印表單錯誤???? –

+0

您的html表單是否具有相應的元素值?嘗試'打印spf.errors'的表單錯誤。對於特定於表單的錯誤,請嘗試:'for k,f in spf.fields.items():for in f.error_messages:print f,e' – Rohan