Mihael Waschl
Mihael Waschl

Reputation: 350

Insert foregin key in django database

I am building django app where user select a company and then application pass company primary key over url. User is than redirect to the page where he can see all company devices and he can add new one to the list. Now I have problem. When I submit the form with all the data, I allways get the same validation error, which tells me that company field is requierd (I added foregin key to the form before validation). What I am doing wrong?

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)

I would be very happy if you can help me with this problem.

Upvotes: 0

Views: 51

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599778

devices_form.company doesn't do anything useful.

If you want to set a value manually, you should exclude it from the form fields altogether, and set it on save.

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)

Upvotes: 1

Debendra
Debendra

Reputation: 1142

I specified in the comments above, you have 3 fields on forms.py and 4 fields on models.py and you specified all fields to use on fields on forms.py.

Change in 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

You can also exclude fields by exclude = ('fields') as per @Daniel Roseman's answer.

Upvotes: 1

Related Questions