'ManyToManyDescriptor'对象在Django 2中没有属性'all'

时间:2018-08-03 13:01:16

标签: django python-3.x django-models django-forms django-views

这是我的表格。py:

class NewsletterCreationForm(forms.ModelForm):
    class Meta:
        model = Newsletter
        fields = ['subject', 'body', 'email', 'status']

这是我的,这是我的通讯模型:

class Newsletter(models.Model):
    EMAIL_STATUS_CHOICES = (
        ('Draft', 'Draft'),
        ('Published', 'Published')
    )
    subject = models.CharField(max_length=256, default='')
    body = models.TextField(default='')
    email = models.ManyToManyField(NewsletterUsers)
    status = models.CharField(max_length=16, choices=EMAIL_STATUS_CHOICES)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.subject

这是我的views.py:

def control_newsletter_delet(request, pk):
    newsletter = get_object_or_404(Newsletter, pk=pk)

    if request.method == 'POST':
        form = NewsletterCreationForm(request.POST, instance=Newsletter)

        if form.is_valid():
            newsletter.delete()
            return redirect('control_newsletter_list')

    else:
        form = NewsletterCreationForm(instance=newsletter)

    context = {
        'form': form,
    }

    return render(request, 'control_panel/control_newsletter_delete.html', context)

现在,当我想使用control_newsletter_delet()时,我会遇到此错误:

'ManyToManyDescriptor' object has no attribute 'all'

我检查了此链接: 'ManyToManyDescriptor' object has no attribute 'all'  它不能帮助我解决我的问题。 有谁知道我为什么会收到这个错误?  此外,很抱歉在我的问题中写错了。

2 个答案:

答案 0 :(得分:1)

问题在于表单不能用于newsletter实例,但是可以用于Newsletter(带有大写字母)类:

def control_newsletter_delet(request, pk):
    newsletter = get_object_or_404(Newsletter, pk=pk)
    if request.method == 'POST':
        form = NewsletterCreationForm(request.POST, instance=newsletter)
        if form.is_valid():
            newsletter.delete()
            return redirect('control_newsletter_list')

    else:
        form = NewsletterCreationForm(instance=newsletter)

    context = {
        'form': form,
    }

    return render(request, 'control_panel/control_newsletter_delete.html', context)

但是,在这里使用表格说的话并没有多大意义:您想删除一个Newsletter,而pk已经确定了新闻简讯是什么,因此我们可以省略表格。尤其是因为它是一种“创造”形式:

def control_newsletter_delet(request, pk):
    newsletter = get_object_or_404(Newsletter, pk=pk)
    if request.method == 'POST':
        newsletter.delete()
        return redirect('control_newsletter_list')

    form = NewsletterCreationForm(instance=newsletter)
    context = {
        'form': form,
    }
    return render(request, 'control_panel/control_newsletter_delete.html', context)

可能form可以完全省略。

答案 1 :(得分:0)

发生此问题是因为我向NewsletterCreationForm传递了额外的参数。 要解决此问题,只需将form = NewsletterCreationForm(request.POST, instance=Newsletter)替换为form = NewsletterCreationForm(request.POST or None)并删除实例。