django - 出现“无属性”错误时如何添加到 ManyToMany?
问题描述
使用表单,在第一次获得要添加的问题的查询集后,我试图将项目添加到对象的多对多字段questions
中。Quiz
我保存了 ModelForm,但是当我添加项目时,我得到了一个 AttributError:'function' object has no attribute 'questions'
以前,我能够使用模型中的保存方法创建一个包含 3 个随机问题的测验对象。但是,我看不到仅使用模型从特定查询集中添加 3 个问题的方法
视图.py
def choose(request, obj_id):
"""Get the id of the LearnObject of interest"""
"""Filter the questions and pick 3 random Qs"""
my_qs = Question.objects.filter(learnobject_id=obj_id)
my_qs = my_qs.order_by('?')[0:3]
if request.method == 'POST':
form = QuizForm(request.POST)
if form.is_valid():
new_quiz = form.save
for item in my_qs:
new_quiz.questions.add(item)
new_quiz.save()
return HttpResponseRedirect('/quizlet/quiz-list')
else:
form = QuizForm()
return render(request, 'quizlet/quiz_form.html', {'form': form})
和models.py
class LearnObject(models.Model):
"""model for the learning objective"""
code = models.CharField(max_length=12)
desc = models.TextField()
class Question(models.Model):
"""model for the questions."""
name = models.CharField(max_length=12)
learnobject = models.ForeignKey(
LearnObject, on_delete=models.CASCADE,
)
q_text = models.TextField()
answer = models.CharField(max_length=12)
class Quiz(models.Model):
"""quiz which will have three questions."""
name = models.CharField(max_length=12)
questions = models.ManyToManyField(Question)
completed = models.DateTimeField(auto_now_add=True)
my_answer = models.CharField(max_length=12)
class QuizForm(ModelForm):
"""test out form for many2many"""
class Meta:
model = Quiz
fields = ['name', 'my_answer']
错误发生在行new_quiz.questions.add(item)
。我不明白这一点,因为模型Quiz
有一个字段questions
,并且对象(我认为)已经在第一个创建new_quiz = form.save()
解决方案
错误在下一行:new_quiz = form.save
,您缺少()
,将其更改为new_quiz = form.save()
。
如果不是,则将函数的引用保存form.save
到new_quiz
, 而不是函数返回的对象。
推荐阅读
- android - 无法实例化 appComponentFactory
- html - 带图像的按钮
- bash - 如何在 Windows 中从 gitbash 运行 jq?
- visual-studio - 值不能为空。参数名称:pUnk
- python - 无法在 scrapy 中使用 frontera 加载初始种子网址
- html - 如何在移动 safari 上实现统一的滚动体验?
- javascript - 未触发提交类型输入的提交事件
- javascript - 更改直接 url 输入的语言 (VueJs)
- java - java.lang.NoSuchMethodError:在类中添加构造函数后
- angular - 使用量角器打字稿,我如何检测这个元素方形白框,然后单击并拖动白框,它有 ng-mousedown 和变换