Django models Django模型从同一模型插入外键
我正在Django中构建一个简单的评论应用程序。该应用程序允许回复评论,并使用相同的模式存储评论和回复。我的问题是,当我尝试插入一个新的回复时,parentpost(FK-to-parent注释)插入为NULL。当我使用admin接口插入回复时,它会正确地存储我选择的parentpost的parentpost ID。因此,我知道问题不在我的模型中,而是在我的观点中 /模型/ /看法/Django models Django模型从同一模型插入外键,django-models,Django Models,我正在Django中构建一个简单的评论应用程序。该应用程序允许回复评论,并使用相同的模式存储评论和回复。我的问题是,当我尝试插入一个新的回复时,parentpost(FK-to-parent注释)插入为NULL。当我使用admin接口插入回复时,它会正确地存储我选择的parentpost的parentpost ID。因此,我知道问题不在我的模型中,而是在我的观点中 /模型/ /看法/ 您正在尝试按id设置parentpost ForeignKey 您应该使用: newPost = UserPos
您正在尝试按id设置parentpost ForeignKey 您应该使用:
newPost = UserPost(name = nameIn, post = postIn, parentpost = parentpostIn)
或(见):
忘了提到我的模板中有ID:{{parentpostIn.ID}},它正确地标识了ID,但是子帖子的insert没有将其作为ForeignKey插入。所以我的观点是访问ID。谢谢你的工作。快速提问。我在管理和使用外键字段的混乱,什么会导致管理员无法更新父帖子?假设我有一个子帖子,父帖子是Test1,当我点击save后尝试将parentpost更新为Test2时,帖子仍然显示Test1???
def reply(request, slugIn):
parentpostIn = UserPost.objects.get(slug = slugIn)
pid = parentpostIn.id
template_name = 'reply.html'
if request.method == 'POST':
form = forms.ReplyPostForm(data = request.POST)
# create a new item
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
if form.is_valid():
nameIn = form.cleaned_data['name']
postIn = form.cleaned_data['post']
newPost = UserPost(name = nameIn, post = postIn, parentpost = pid)
newPost.save()
return render_to_response(template_name, locals(), context_instance = RequestContext(request))
else:
# This the the first page load, display a blank form
form = forms.NewPostForm()
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
newPost = UserPost(name = nameIn, post = postIn, parentpost = parentpostIn)
newPost = UserPost(name = nameIn, post = postIn)
newPost.parentpost_id = pid