【发布时间】:2022-08-03 17:51:21
【问题描述】:
当我保存我的 NoteForm 时,我想保存我的表单和 \"note\" 字段,然后我想在 NoteTagModel 中为 Note 创建一个 \"tag\"。
目前,我创建了一个新标签,但它没有分配给笔记。我知道下面的代码一定是错误的:
notetag.id = new_note_parse.id
如果我改为:
notetag.note = new_note_parse.id
我收到以下错误:
\"NoteTagModel.note\" must be a \"NoteModel\" instance.
下面是我的视图.py:
def notes(request):
note_form = NoteForm
notetag = NoteTagModel()
note_form=NoteForm(request.POST)
if note_form.is_valid():
new_note = note_form.save(commit=False)
new_note_parse = new_note
new_note.save()
notetag.id = new_note_parse.id
notetag.tag = \"Test\"
notetag.save()
return HttpResponseRedirect(reverse(\'notes:notes\'))
context = {
\'note_form\' : note_form,
\'notes\' : NoteModel.objects.all(),
\'notes_tag\' : NoteTagModel.objects.all(),
}
return render(request, \"notes/notes.html\", context)
我的模型.py是:
class NoteModel(models.Model):
note = models.CharField(
max_length = 5000
)
def __str__(self):
return f\"{self.note}\"
class NoteTagModel(models.Model):
note = models.ForeignKey(
NoteModel,
on_delete=models.CASCADE,
related_name=\"notes\",
blank= False,
null = True,
)
tag = models.CharField(
max_length = 5000
)
def __str__(self):
return f\"Note: {self.note} | Tag: {self.tag}\"
我有以下内容表格.py:
class NoteForm(ModelForm):
class Meta:
model = NoteModel
fields = [
\'note\',
]
标签: mysql django django-models