在此处输入图像描述
如何访问views.py中的savedata.project_detail?每个用户将拥有他想要的任意数量的项目。每个项目都有一个唯一的主键。我想访问defchecklist(request(函数中的主键。我只得到模型属性";checked_value";来自html模板。另一个属性";project_detail";应该自动获取主键pf模型";项目";。但我不知道如何在defchecklist函数中获取模型项目的主键。如果有人能在这里帮忙的话。
这是型号.py
class project(models.Model):
project_name = models.CharField(max_length = 20)
date = models.DateField(("Date"), default=datetime.date.today)
user = models.ForeignKey(User, on_delete=models.CASCADE)
class check_done(models.Model):
checked_value = models.CharField(max_length = 200)
project_detail = models.ForeignKey(project, to_field="id", db_column="project_detail", on_delete=models.CASCADE)
这是视图.py
def show(request):
log_user = request.user
projects = project.objects.filter(user=log_user)
return render(request, 'project.html',{'p':projects})
@login_required(login_url='/login/')
def add(request):
if request.method == "POST":
data = request.POST['data']
new = project(project_name = data, user=request.user)
new.save()
return render(request, 'addproject.html')
else:
return render(request, 'addproject.html')
@login_required(login_url='/login/')
def checklist(request):
if request.method == "POST":
savedata = check_done()
savedata.project_detail = ??
print(savedata.project_detail)
savedata.checked_value = request.POST.get('abc')
savedata.save()
return render(request, 'checklist.html')
else:
return render(request, 'checklist.html')
您需要为savedata.project_detail属性分配一个项目模型:
@login_required(login_url='/login/')
def checklist(request):
if request.method == "POST":
savedata = check_done()
savedata.project_detail = project.objects.get(id=request.POST['project_detail_id'])
savedata.checked_value = request.POST.get('abc')
savedata.save()
return render(request, 'checklist.html')
else:
return render(request, 'checklist.html')
我认为您可以创建或获取要和savedata
对象关联的project
对象,并将其直接分配给project_detail
属性,也可以将项目主键分配给project_detail_id
属性。