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

                      Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                      Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                      How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page