python - Django ModelForm 无法使用 ModelForm 和 save_m2m 保存 "many to many"记录

标签 python django modelform manytomanyfield

我是 Django 的新手,正在使用这个项目来学习它。我能够保存日志记录,但多对多关系不起作用。

这个“创建” View 显示了正确的形式,包括带有所有列出的加密货币的多选框(来自加密模型)。提交表单时,多对多记录不保存,但日志保存正常。

我找到了很多不同的答案,有些是针对 python 2.7 的,但这是基于 [Django 文档][1] 的最简单的方法。非常感谢任何帮助。

另外,这种关系在管理部分工作得很好,所以我认为它与表单和/或 View 和保存有关。

模型.py

from django.db import models
from crypto.models import Crypto as CryptoModel

class Journal(models.Model):
    title = models.CharField(max_length=200, help_text='Journal Title', blank=False, null=False)
    content = models.TextField(max_length=2000, help_text='Journal Content (HTML OK)', blank=False, null=False)
    crypto_id = models.ManyToManyField(CryptoModel, blank=True)    
    created = models.DateTimeField(help_text='Created', auto_now_add=True, null=True)

    def __str__(self):
        return self.title  ## String for representing the Model object, usually name field or title

表单.py

from django.forms import ModelForm, ModelMultipleChoiceField, widgets
from journal.models import Journal as JournalModel
from crypto.models import Crypto as CryptoModel

class JournalForm(ModelForm):
    # select multiple items box
    cryptos = ModelMultipleChoiceField(widget=widgets.SelectMultiple(attrs={'size': 30}), queryset=CryptoModel.objects.all())

    class Meta:
        model = JournalModel
        fields = [
            "title",
            "content",
        ]
        labels = {
            'title': 'Journal Title',
        }
        required = [
            "title", # same as model
            "content",  # same as model
        ]

views.py

from journal.forms import JournalForm
from django.utils import timezone
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect, get_object_or_404
from journal.models import Journal as JournalModel

    def Create(request):

        if request.method == "POST":
            form = JournalForm(request.POST) # form instance
            context = {'form': form} # if errors, keep the form data on next page load

            journal = form.save(commit=False)  # False needed for many-to-many
            journal.title = form.cleaned_data["title"]
            journal.content = form.cleaned_data["content"]
            journal.created = timezone.now()
            journal.save()  # save the form journal data, now we have a PK
            form.save_m2m()  # save the 'form' using ManytoMany method

            return HttpResponseRedirect('/journal/')

        form = JournalForm()
        context = {'form': form}

        return render(request, 'journal/create.html', context)

模型.py 2

from django.db import models
from crypto.models import Crypto

class Journal(models.Model):
    title = models.CharField(max_length=200, help_text='Journal Title', blank=False, null=False)
    content = models.TextField(max_length=2000, help_text='Journal Content (HTML OK)', blank=False, null=False)
    crypto_id = models.ManyToManyField(Crypto, blank=True)    
    created = models.DateTimeField(help_text='Created', auto_now_add=True, null=True)

    def __str__(self):
        return self.title  ## String for representing the Model object, usually name field or title

表格.py 2

from django.forms import ModelForm, ModelMultipleChoiceField, widgets
from journal.models import Journal
from crypto.models import Crypto

class JournalForm(ModelForm):
    # select multiple items box
cryptos = ModelMultipleChoiceField(widget=widgets.SelectMultiple(attrs={'size': 30}), queryset=Crypto.objects.all())

class Meta:
    model = JournalModel
    fields = [
        "title",
        "content",
        "cryptos",
    ]

views.py 2

from journal.forms import JournalForm
from django.utils import timezone
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect, get_object_or_404
from journal.models import Journal

def Create(request):

    if request.method == "POST":
        form = JournalForm(request.POST) # form instance
        context = {'form': form} # if errors, keep the form data on next page load

        journal = form.save(commit=False)  # False needed for many-to-many
        journal.created = timezone.now()
        journal.save()  # save the form journal data, now we have a PK

        journal.crypto_id.set(form.cleaned_data.get("cryptos")) # must be after "save"
        form.save_m2m()  # save the 'form' using ManytoMany method

        return HttpResponseRedirect('/journal/')

    form = JournalForm()
    context = {'form': form}

    return render(request, 'journal/create.html', context)

最佳答案

希望这能解决您的问题,但是在保存您的日志实例后这一行 journal.crypto_id.set(form.cleaned_data.get("cryptos"))

关于python - Django ModelForm 无法使用 ModelForm 和 save_m2m 保存 "many to many"记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53015096/

相关文章:

python - 更改子图中的绘图大小

html - django-tables2 每行添加按钮

python - django ModelForm save() 方法问题

Django : ModelForm Pre-populate Checkbox with Custom Query

python - 为什么 django 项目是 python 包?

python - postgres 中的锁定机制/postgres 中的死锁。 [我正在使用 sqlalchemy]

python - 将默认值设置为稀疏 scipy 矩阵

linux - 如何找到 Django 包

python - 如何将 python 站点迁移到另一台机器?

django - 在django中上传图片时出错: "coercing to Unicode: need string or buffer, tuple found"