一尘不染

通过Django中的模型表单保存多对多数据

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中处理发布请求:

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'))

每当我通过表单保存时,只有Notes文本字段都会保存在PHIssue实例中,并且许多字段都是空白。有人可以帮我找出问题所在吗?


阅读 566

收藏
2020-03-29

共1个答案

一尘不染

使用时commit=False,你必须致电save_m2m()

m2m关系要求先保存父对象,而你并没有使用 commit=False

2020-03-29