我有一个web服务,我想将rdp配置文件添加到某个合同号。
views.py
from django.shortcuts import render
from program.models import contract,rdp
from django.contrib.auth.decorators import login_required
@login_required(login_url='login')
def add_rdp(request):
if request.method == "POST":
get_rdp = (request.POST.get('rdp', ''))
get_number = (request.POST.get('contract_number',''))
new_rdp = rdp(config = get_rdp).save()
for new_contract in contract.objects.filter(number = get_number):
new_rdp.contract.add(new_contract)
return render(request, 'add_rdp.html')
models.py
class contract(models.Model):
server = models.ForeignKey(server)
number = models.CharField(unique = True, max_length = 64)
class rdp(models.Model):
contract = models.ForeignKey(contract)
config = models.TextField()
这是我得到的错误:
Integrity Error
(1048, "Column 'contract_id' cannot be null")
由于这种方法适用于我在Django的另一个webapp,我无法弄清楚为什么这不起作用。
答案 0 :(得分:1)
因为您在没有合同时致电save()
。
您可以更改模型的定义:
class rdp(models.Model):
contract = models.ForeignKey(contract, blank = True)
config = models.TextField()
答案 1 :(得分:1)
您必须获取模型实例,然后将其添加到您的' new_rdp'中。你可以这样做:
@login_required(login_url='login')
def add_rdp(request):
if request.method == "POST":
get_rdp = (request.POST.get('rdp', ''))
get_number = (request.POST.get('contract_number',''))
for new_contract in contract.objects.all():
if new_contract.number == get_number:
new_rdp = rdp(config = get_rdp, contract = new_contract).save()
return render(request, 'add_rdp.html')