在Django数据库中插入foregin密钥

时间:2019-03-08 13:09:58

标签: python django database postgresql

我正在构建django应用程序,用户选择公司,然后应用程序通过url传递公司主键。然后,用户将重定向到该页面,在该页面上他可以看到所有公司设备,并且可以将新设备添加到列表中。现在我有问题了。当我提交包含所有数据的表单时,我总是收到相同的验证错误,这告诉我要求公司字段(我在验证之前在表单中添加了foregin键)。我在做什么错了?

views.py:

def network_devices(request, pk=None):
    if pk:
        if request.method == 'POST':

            if 'dodajnapravo' in request.POST:
                devices_form = AddNetworkDevice(request.POST)
                devices_form.company = pk
                if devices_form.is_valid():
                    devices_form.save()
                    return redirect(network_devices)

                else:
                    messages.error(request, 'Vnešeni podatki niso pravilni!')
                    return redirect(network_devices)

        elif request.method == 'GET':
            devices_form = AddNetworkDevice()
            devices = NetworkDevices.objects.filter(company_id=pk).all()
            print(devices)
            return render(request, 'interface/network_devices.html', {'device_form': devices_form, 'page_title': 'Naprave',
                                                                  'devices': devices})

    else:
         return redirect(add_select_company)

forms.py:

class AddNetworkDevice(forms.ModelForm):
     vendor = forms.CharField(required=True, label='Proizvajalec', max_length=100)
     product = forms.CharField(required=True, label='Produkt', max_length=100)
     version = forms.CharField(required=False, label='Verzija', max_length=50)

    class Meta:
         model = NetworkDevices
         fields = ('__all__')

models.py:

class Company(models.Model):
    class Meta:
        verbose_name_plural = 'Podjetja'

    company_name = models.CharField(max_length=150)
    company_addres = models.CharField(max_length=500)

    def __str__(self):
        return str('{}').format(self.company_name)


class NetworkDevices(models.Model):
    class Meta:
        verbose_name_plural = 'Naprave v Omrežju'

    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    vendor = models.CharField(max_length=100)
    product = models.CharField(max_length=100)
    version = models.CharField(max_length=50)

如果您能帮助我解决这个问题,我将非常高兴。

2 个答案:

答案 0 :(得分:1)

我在上面的注释中指定了,您在forms.py上有3个字段,在models.py上有4个字段,并且您指定了所有fields用于forms.py上的字段。 / p>

更改forms.py

class AddNetworkDevice(forms.ModelForm):
     vendor = forms.CharField(required=True, label='Proizvajalec', max_length=100)
     product = forms.CharField(required=True, label='Produkt', max_length=100)
     version = forms.CharField(required=False, label='Verzija', max_length=50)

    class Meta:
         model = NetworkDevices
         fields = ('vendor', 'product', 'version')  # here is your problem

您也可以按照@Daniel Roseman的回答,用exclude = ('fields')排除字段。

答案 1 :(得分:1)

devices_form.company没什么用。

如果您要手动设置一个值,则应将其从表单字段中完全排除,并在保存时进行设置。

class AddNetworkDevice(forms.ModelForm):
    ...
    class Meta:
        model = NetworkDevices
        exclude = ('company',)

...

       if 'dodajnapravo' in request.POST:
            devices_form = AddNetworkDevice(request.POST)
            if devices_form.is_valid():
                device = devices_form.save(commit=False)
                device.company_id = pk
                device.save()
                return redirect(network_devices)