Insert foregin key in django database The Next CEO of Stack OverflowHow does database indexing work?Does Django scale?Add new keys to a dictionary?Check if a given key already exists in a dictionaryShow information of subclass in list_display djangoDjango south migration error with unique field in postgresql databaseRadio buttons in django adminHow to expose some specific fields of model_b based on a field of model_a?How to set dynamic initial values to django modelform fieldHow to define Mode with generic ForeignKey in Django

Can a caster that cast Polymorph on themselves stop concentrating at any point even if their Int is low?

Is HostGator storing my password in plaintext?

How can I quit an app using Terminal?

Why is there a PLL in CPU?

% symbol leads to superlong (forever?) compilations

Should I tutor a student who I know has cheated on their homework?

Increase performance creating Mandelbrot set in python

If I blow insulation everywhere in my attic except the door trap, will heat escape through it?

Is it my responsibility to learn a new technology in my own time my employer wants to implement?

How to be diplomatic in refusing to write code that breaches the privacy of our users

Customer Requests (Sometimes) Drive Me Bonkers!

Failed to fetch jessie backports repository

How to make a software documentation "officially" citable?

Where to find order of arguments for default functions

Text adventure game code

Need some help with wall behind rangetop

How do I go from 300 unfinished/half written blog posts, to published posts?

What does "Its cash flow is deeply negative" mean?

Trouble understanding the speech of overseas colleagues

Which organization defines CJK Unified Ideographs?

Rotate a column

What is the point of a new vote on May's deal when the indicative votes suggest she will not win?

Why didn't Khan get resurrected in the Genesis Explosion?

The King's new dress



Insert foregin key in django database



The Next CEO of Stack OverflowHow does database indexing work?Does Django scale?Add new keys to a dictionary?Check if a given key already exists in a dictionaryShow information of subclass in list_display djangoDjango south migration error with unique field in postgresql databaseRadio buttons in django adminHow to expose some specific fields of model_b based on a field of model_a?How to set dynamic initial values to django modelform fieldHow to define Mode with generic ForeignKey in Django










0















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.










share|improve this question



















  • 1





    You have 3 filelds on forms.py and 4 fields on models.py and you specified all fields to use on fields on forms.py.

    – Debendra
    Mar 8 at 13:21
















0















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.










share|improve this question



















  • 1





    You have 3 filelds on forms.py and 4 fields on models.py and you specified all fields to use on fields on forms.py.

    – Debendra
    Mar 8 at 13:21














0












0








0








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.










share|improve this question
















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.







python django database postgresql






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 13:24







Mihael Waschl

















asked Mar 8 at 13:09









Mihael WaschlMihael Waschl

437




437







  • 1





    You have 3 filelds on forms.py and 4 fields on models.py and you specified all fields to use on fields on forms.py.

    – Debendra
    Mar 8 at 13:21













  • 1





    You have 3 filelds on forms.py and 4 fields on models.py and you specified all fields to use on fields on forms.py.

    – Debendra
    Mar 8 at 13:21








1




1





You have 3 filelds on forms.py and 4 fields on models.py and you specified all fields to use on fields on forms.py.

– Debendra
Mar 8 at 13:21






You have 3 filelds on forms.py and 4 fields on models.py and you specified all fields to use on fields on forms.py.

– Debendra
Mar 8 at 13:21













2 Answers
2






active

oldest

votes


















1














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)





share|improve this answer






























    1














    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.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55063910%2finsert-foregin-key-in-django-database%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      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)





      share|improve this answer



























        1














        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)





        share|improve this answer

























          1












          1








          1







          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)





          share|improve this answer













          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)






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 8 at 13:27









          Daniel RosemanDaniel Roseman

          458k42594653




          458k42594653























              1














              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.






              share|improve this answer



























                1














                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.






                share|improve this answer

























                  1












                  1








                  1







                  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.






                  share|improve this answer













                  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.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 8 at 13:27









                  DebendraDebendra

                  331412




                  331412



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55063910%2finsert-foregin-key-in-django-database%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

                      Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                      2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived