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

发布于 2024-10-31 13:54:49 字数 2404 浏览 4 评论 0原文

我在从表单中保存多对多字段时遇到问题。这是我的模型:

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

在这里,我在 view.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'))

每当我通过表单保存时,只有 Notes 文本字段会保存在 PHIssue 实例中,而多对多字段则留空。有人可以帮我找出问题所在吗?

I have a problem saving many to many fields from a form. Here are my models:

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

And here I process the post request in my 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'))

Whenever I save through the form, only the Notes text field gets saved in the PHIssue instance, and the many to many fields are left blank. Can someone help me find what is wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

只为一人 2024-11-07 13:54:49

http://docs.djangoproject.com/en/ dev/topics/forms/modelforms/#the-save-method

使用 commit=False 时,必须调用 save_m2m()

m2m 关系需要父级首先要保存的对象,您没有使用 commit=False 来执行此操作

http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method

When using commit=False, you have to call save_m2m()

m2m relationships require the parent object to be saved first, which you are not doing by using commit=False

披肩女神 2024-11-07 13:54:49

你可以这样做
例如:

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

You can do like this
for example:

  if todo_list_form.is_valid():
                todo_list = todo_list_form.save(commit=False)
                todo_list.save()
                todo_list_form.save_m2m()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文