这是我的forms.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'
它不能帮助我解决我的问题。
有谁知道我为什么会收到这个错误?
另外,对于我在问题中写错了我感到抱歉。
最佳答案
问题在于该表单不适用于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
可能会完全省略。关于django - 'ManyToManyDescriptor'对象在django 2中没有属性'all',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51673267/