Django 无法保存子对象的父 ID
Posted
技术标签:
【中文标题】Django 无法保存子对象的父 ID【英文标题】:Django can't save parent id of child objects 【发布时间】:2021-11-15 21:00:33 【问题描述】:当表格将被保存时,我想保存父 ID,但我不明白我在哪里做错了。我正在使用<input type="hidden" name="parent" id=i.sno>
保存父 ID,如果我从浏览器检查 html,我可以看到 ID 号。
models.py
class Contact(MPTTModel):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True,related_name='contact_user')
parent =TreeForeignKey('self', on_delete=models.CASCADE,
null=True, blank=True, related_name='contact_parent')
sno = models.AutoField(primary_key=True,)
#my others fields....
forms.py
class TicketForm(forms.ModelForm):
class Meta:
model = Contact
fields = ['message','parent','sno','existing_customer','technical_service']
views.py
def SupportPageView(request):
if request.method == "POST":
support_form = TicketForm(request.POST or None)
if support_form.is_valid():
isinstance = support_form.save(commit=False)
isinstance.user = request.user
isinstance.name = request.user.first_name
isinstance.email = request.user.email
isinstance.save()
name = request.user.first_name
messages.add_message(request, messages.INFO, f'name Thanks for your message. We will get back to you very soon')
return redirect('contact:support-ticket')
else:
support_form = TicketForm()
user = request.user
support_object = Contact.objects.filter(user=user)
context = "support_form":support_form,'support_object':support_object
return render(request,"contact/support.html",context)
HTML
%for i in support_object%
<form method="POST">
%csrf_token%
<textarea name="message" class="form-control" style="height: 150px;"></textarea><br>
<input type="hidden" name="parent" id=i.sno>
<button type="submit" class="btn btn-info">Submit</button>
</form>
%endfor%
我的表单正在保存为父级,但我希望它们将保存为子级。
【问题讨论】:
有什么问题? Rvector 阅读了这个问题。我描述了一切 【参考方案1】:我在 html 字段中做错了
我使用的是<input type="hidden" name="parent" id=i.sno>
但它应该是 <input type="hidden" name="parent" id="parent_id" value="i.sno">
。我的 html 字段中缺少值
【讨论】:
以上是关于Django 无法保存子对象的父 ID的主要内容,如果未能解决你的问题,请参考以下文章