2011-04-10 61 views
17

我從保存表單中的多個字段時遇到問題。這裏是我的模型:通過Django中的模型保存多對多數據

class TextIssue(models.Model): 
    Issue = models.CharField(max_length=150, unique=True) 

    def __unicode__(self): 
     return self.Issue 

class PadIssue(models.Model): 
    Issue = models.CharField(max_length=150, unique=True) 

    def __unicode__(self): 
     return self.Issue 


class PHIssue(models.Model): 
    Data = models.ForeignKey(Data) 
    TextIssue = models.ManyToManyField(TextIssue, blank=True, null=True) 
    PadIssue = models.ManyToManyField(PadIssue, blank=True, null=True) 
    Notes = models.TextField() 

    def clean(self): 
     from django.core.exceptions import ValidationError 
     if self.TextIssue is None and self.PadIssue is None: 
      raise ValidationError('You must choose at least one issue category.') 

     if self.Notes is None: 
      raise ValidationError('You must write a note regarding the issues selected above.') 


class PHIssueForm(ModelForm): 

    class Meta: 
     model = PHIssue 
     exclude = ('Data',) 

在這裏,我在處理我的views.py POST請求:

def process_npiform(request, npi_id=None): 

    if npi_id: 

     try: 
      npi = Data.objects.get(id=int(npi_id)) 
     except: 

      raise Http404 

    if request.method == 'POST': 
     data = DataForm(request.POST, instance=npi, prefix='npi_data') 

     if data.is_valid(): 
      update = data.save(commit=False) 

      if not request.user.is_superuser: 
       update.User = request.user 

      update.save() 

      if update.Status == 'past-due': 

       try: 
        prefab = PHIssue.objects.get(Data=npi) 

       except: 
        prefab = PHIssue(Data=Data.objects.get(id=int(update.id))) 
        prefab.save() 

       issue = PHIssueForm(request.POST, instance=prefab, prefix='npi_issue') 

       if issue.is_valid(): 

        save_issue = issue.save(commit=False) 

        save_issue.save() 




      return HttpResponseRedirect(reverse('pm')) 

     else: 
      return render_to_response('npi/data.html', {'data': data, 'issue': issue}, context_instance=RequestContext(request))  
    else: 
     return HttpResponseRedirect(reverse('pm')) 

每當我通過保存的形式,只說明文本字段被保存在PHIssue實例,許多領域都留空。有人能幫我找出有什麼問題嗎?

回答

9

做你可以這樣做 例如:

if todo_list_form.is_valid(): 
       todo_list = todo_list_form.save(commit=False) 
       todo_list.save() 
       todo_list_form.save_m2m()