Get the list of related objects in django












0















I have 3 models:



class Node(models.Model):
ID = models.DecimalField(max_digits=19, decimal_places=10)
name = models.CharField(default='node', max_length=32)
connexion = models.CharField(max_length=255)
# Many2one fields | Foreign keys:
firm = models.ForeignKey('firme.Firme', on_delete=models.CASCADE, null=True, blank=True)


class ScheduledAction(models.Model):
date = models.DateTimeField(default=datetime.now, blank=True)
firm = models.ForeignKey('firme.Firme', on_delete=models.CASCADE, null=True, blank=True)
node_ids = models.ManyToManyField(Node)


I want in ScheduledAction form to show, for a selected firm, the list of its related nodes. Normally I should do this by get:



class ScheduledActionForm(forms.ModelForm):
date = forms.DateTimeField()
firm = forms.ModelChoiceField(queryset=Firme.objects.all())
node_ids = forms.ModelMultipleChoiceField(queryset=Node.objects.get(firm_id=firm.id), widget=forms.CheckboxSelectMultiple)

class Meta:
model = ScheduledAction
fields = [
'date',
'firm',
'node_ids'
]


This is my views.py:



def planification_view(request, id):
scheduledAction = ScheduledActionForm(request.POST or None)
firme = get_object_or_404(Firme, id=id)
nodes = Node.objects.all()
if scheduledAction.is_valid():
scheduledAction.save()
print('formulaire enregistre')
scheduledAction = ScheduledActionForm()
context = {
'firme': firme,
'form': scheduledAction,
'nodes': nodes
}
return render(request, "node/planification.html", context)


But I got this error:



AttributeError: 'ModelChoiceField' object has no attribute 'id'


How can I fix this?










share|improve this question





























    0















    I have 3 models:



    class Node(models.Model):
    ID = models.DecimalField(max_digits=19, decimal_places=10)
    name = models.CharField(default='node', max_length=32)
    connexion = models.CharField(max_length=255)
    # Many2one fields | Foreign keys:
    firm = models.ForeignKey('firme.Firme', on_delete=models.CASCADE, null=True, blank=True)


    class ScheduledAction(models.Model):
    date = models.DateTimeField(default=datetime.now, blank=True)
    firm = models.ForeignKey('firme.Firme', on_delete=models.CASCADE, null=True, blank=True)
    node_ids = models.ManyToManyField(Node)


    I want in ScheduledAction form to show, for a selected firm, the list of its related nodes. Normally I should do this by get:



    class ScheduledActionForm(forms.ModelForm):
    date = forms.DateTimeField()
    firm = forms.ModelChoiceField(queryset=Firme.objects.all())
    node_ids = forms.ModelMultipleChoiceField(queryset=Node.objects.get(firm_id=firm.id), widget=forms.CheckboxSelectMultiple)

    class Meta:
    model = ScheduledAction
    fields = [
    'date',
    'firm',
    'node_ids'
    ]


    This is my views.py:



    def planification_view(request, id):
    scheduledAction = ScheduledActionForm(request.POST or None)
    firme = get_object_or_404(Firme, id=id)
    nodes = Node.objects.all()
    if scheduledAction.is_valid():
    scheduledAction.save()
    print('formulaire enregistre')
    scheduledAction = ScheduledActionForm()
    context = {
    'firme': firme,
    'form': scheduledAction,
    'nodes': nodes
    }
    return render(request, "node/planification.html", context)


    But I got this error:



    AttributeError: 'ModelChoiceField' object has no attribute 'id'


    How can I fix this?










    share|improve this question



























      0












      0








      0








      I have 3 models:



      class Node(models.Model):
      ID = models.DecimalField(max_digits=19, decimal_places=10)
      name = models.CharField(default='node', max_length=32)
      connexion = models.CharField(max_length=255)
      # Many2one fields | Foreign keys:
      firm = models.ForeignKey('firme.Firme', on_delete=models.CASCADE, null=True, blank=True)


      class ScheduledAction(models.Model):
      date = models.DateTimeField(default=datetime.now, blank=True)
      firm = models.ForeignKey('firme.Firme', on_delete=models.CASCADE, null=True, blank=True)
      node_ids = models.ManyToManyField(Node)


      I want in ScheduledAction form to show, for a selected firm, the list of its related nodes. Normally I should do this by get:



      class ScheduledActionForm(forms.ModelForm):
      date = forms.DateTimeField()
      firm = forms.ModelChoiceField(queryset=Firme.objects.all())
      node_ids = forms.ModelMultipleChoiceField(queryset=Node.objects.get(firm_id=firm.id), widget=forms.CheckboxSelectMultiple)

      class Meta:
      model = ScheduledAction
      fields = [
      'date',
      'firm',
      'node_ids'
      ]


      This is my views.py:



      def planification_view(request, id):
      scheduledAction = ScheduledActionForm(request.POST or None)
      firme = get_object_or_404(Firme, id=id)
      nodes = Node.objects.all()
      if scheduledAction.is_valid():
      scheduledAction.save()
      print('formulaire enregistre')
      scheduledAction = ScheduledActionForm()
      context = {
      'firme': firme,
      'form': scheduledAction,
      'nodes': nodes
      }
      return render(request, "node/planification.html", context)


      But I got this error:



      AttributeError: 'ModelChoiceField' object has no attribute 'id'


      How can I fix this?










      share|improve this question
















      I have 3 models:



      class Node(models.Model):
      ID = models.DecimalField(max_digits=19, decimal_places=10)
      name = models.CharField(default='node', max_length=32)
      connexion = models.CharField(max_length=255)
      # Many2one fields | Foreign keys:
      firm = models.ForeignKey('firme.Firme', on_delete=models.CASCADE, null=True, blank=True)


      class ScheduledAction(models.Model):
      date = models.DateTimeField(default=datetime.now, blank=True)
      firm = models.ForeignKey('firme.Firme', on_delete=models.CASCADE, null=True, blank=True)
      node_ids = models.ManyToManyField(Node)


      I want in ScheduledAction form to show, for a selected firm, the list of its related nodes. Normally I should do this by get:



      class ScheduledActionForm(forms.ModelForm):
      date = forms.DateTimeField()
      firm = forms.ModelChoiceField(queryset=Firme.objects.all())
      node_ids = forms.ModelMultipleChoiceField(queryset=Node.objects.get(firm_id=firm.id), widget=forms.CheckboxSelectMultiple)

      class Meta:
      model = ScheduledAction
      fields = [
      'date',
      'firm',
      'node_ids'
      ]


      This is my views.py:



      def planification_view(request, id):
      scheduledAction = ScheduledActionForm(request.POST or None)
      firme = get_object_or_404(Firme, id=id)
      nodes = Node.objects.all()
      if scheduledAction.is_valid():
      scheduledAction.save()
      print('formulaire enregistre')
      scheduledAction = ScheduledActionForm()
      context = {
      'firme': firme,
      'form': scheduledAction,
      'nodes': nodes
      }
      return render(request, "node/planification.html", context)


      But I got this error:



      AttributeError: 'ModelChoiceField' object has no attribute 'id'


      How can I fix this?







      django django-models django-forms






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 2 at 10:32







      Tessnim

















      asked Jan 2 at 10:00









      TessnimTessnim

      146117




      146117
























          1 Answer
          1






          active

          oldest

          votes


















          2














          There are several things wrong with your approach



          first of all: you assigned the variable 'firm' to a form field and then using that same variable to get an object from the db won't work in anyway. The variable 'firm' in Node.objects.get(firm_id=firm.id) should be a firm instance.



          second: queryset=Node.objects.get(firm_id=firm.id) won't work because Model.objects.get() will return an object not a query set.



          If you want to show all the nodes for a specific Firm you will need to pass the firm object (or id or other identifier) to the form by for example passing it through the get_form_kwargs() if you are using CBV and filtering by it Node.objects.filter(firm_id=firm.id)



          Update:
          Since you are using function based views there might be a more dry way to do this, but I'm only used to working with CBV so I'll try my best



          On the form we will declare a new variable called firme (we will pass this to the form in your view)



          class ScheduledActionForm(forms.ModelForm):

          def __init__(self, *args, **kwargs):
          self.firme = kwargs.pop('firme')
          super(ScheduledActionForm, self).__init__(*args, **kwargs)
          self.fields['node_ids'].queryset = Node.objects.filter(firm_id=self.firme.id)

          date = forms.DateTimeField()
          firm = forms.ModelChoiceField(queryset=Firme.objects.all()) # why do you want a list of all firms here? Or do you want a single object?
          node_ids = forms.ModelMultipleChoiceField(queryset=Node.objects.none()), widget=forms.CheckboxSelectMultiple)

          class Meta:
          model = ScheduledAction
          fields = [
          'date',
          'firm',
          'node_ids'
          ]


          now for you view:



          def planification_view(request, id):
          firme = get_object_or_404(Firme, id=id)
          nodes = Node.objects.all()
          if request.method == 'POST':
          form = ScheduledActionForm(data=request.POST, firme=firme)
          if form.is_valid():
          scheduledAction = form.save()
          print('formulaire enregistre')
          else:
          form = ScheduledActionForm(firme=firme)

          context = {
          'firme': firme,
          'form': form,
          'nodes': nodes
          }
          return render(request, "node/planification.html", context)


          Something along these lines should get you going. It might still require some tweaking to get it to work in your project. If you still have trouble understanding please read the Django docs and or do their tutorial



          Update 2:
          Not the prettiest solution but it works for the OP






          share|improve this answer


























          • I'm new to Django, can you please explain your solution in detail? Thanks.

            – Tessnim
            Jan 2 at 10:20











          • can you show me the view you use to render the form?

            – Matt
            Jan 2 at 10:30











          • I updated my post and added my view function.

            – Tessnim
            Jan 2 at 10:33













          • I just updated my answer!

            – Matt
            Jan 2 at 10:57











          • I tried your code and got this error: NameError: name 'firme' is not defined

            – Tessnim
            Jan 2 at 11:33











          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%2f54004320%2fget-the-list-of-related-objects-in-django%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          There are several things wrong with your approach



          first of all: you assigned the variable 'firm' to a form field and then using that same variable to get an object from the db won't work in anyway. The variable 'firm' in Node.objects.get(firm_id=firm.id) should be a firm instance.



          second: queryset=Node.objects.get(firm_id=firm.id) won't work because Model.objects.get() will return an object not a query set.



          If you want to show all the nodes for a specific Firm you will need to pass the firm object (or id or other identifier) to the form by for example passing it through the get_form_kwargs() if you are using CBV and filtering by it Node.objects.filter(firm_id=firm.id)



          Update:
          Since you are using function based views there might be a more dry way to do this, but I'm only used to working with CBV so I'll try my best



          On the form we will declare a new variable called firme (we will pass this to the form in your view)



          class ScheduledActionForm(forms.ModelForm):

          def __init__(self, *args, **kwargs):
          self.firme = kwargs.pop('firme')
          super(ScheduledActionForm, self).__init__(*args, **kwargs)
          self.fields['node_ids'].queryset = Node.objects.filter(firm_id=self.firme.id)

          date = forms.DateTimeField()
          firm = forms.ModelChoiceField(queryset=Firme.objects.all()) # why do you want a list of all firms here? Or do you want a single object?
          node_ids = forms.ModelMultipleChoiceField(queryset=Node.objects.none()), widget=forms.CheckboxSelectMultiple)

          class Meta:
          model = ScheduledAction
          fields = [
          'date',
          'firm',
          'node_ids'
          ]


          now for you view:



          def planification_view(request, id):
          firme = get_object_or_404(Firme, id=id)
          nodes = Node.objects.all()
          if request.method == 'POST':
          form = ScheduledActionForm(data=request.POST, firme=firme)
          if form.is_valid():
          scheduledAction = form.save()
          print('formulaire enregistre')
          else:
          form = ScheduledActionForm(firme=firme)

          context = {
          'firme': firme,
          'form': form,
          'nodes': nodes
          }
          return render(request, "node/planification.html", context)


          Something along these lines should get you going. It might still require some tweaking to get it to work in your project. If you still have trouble understanding please read the Django docs and or do their tutorial



          Update 2:
          Not the prettiest solution but it works for the OP






          share|improve this answer


























          • I'm new to Django, can you please explain your solution in detail? Thanks.

            – Tessnim
            Jan 2 at 10:20











          • can you show me the view you use to render the form?

            – Matt
            Jan 2 at 10:30











          • I updated my post and added my view function.

            – Tessnim
            Jan 2 at 10:33













          • I just updated my answer!

            – Matt
            Jan 2 at 10:57











          • I tried your code and got this error: NameError: name 'firme' is not defined

            – Tessnim
            Jan 2 at 11:33
















          2














          There are several things wrong with your approach



          first of all: you assigned the variable 'firm' to a form field and then using that same variable to get an object from the db won't work in anyway. The variable 'firm' in Node.objects.get(firm_id=firm.id) should be a firm instance.



          second: queryset=Node.objects.get(firm_id=firm.id) won't work because Model.objects.get() will return an object not a query set.



          If you want to show all the nodes for a specific Firm you will need to pass the firm object (or id or other identifier) to the form by for example passing it through the get_form_kwargs() if you are using CBV and filtering by it Node.objects.filter(firm_id=firm.id)



          Update:
          Since you are using function based views there might be a more dry way to do this, but I'm only used to working with CBV so I'll try my best



          On the form we will declare a new variable called firme (we will pass this to the form in your view)



          class ScheduledActionForm(forms.ModelForm):

          def __init__(self, *args, **kwargs):
          self.firme = kwargs.pop('firme')
          super(ScheduledActionForm, self).__init__(*args, **kwargs)
          self.fields['node_ids'].queryset = Node.objects.filter(firm_id=self.firme.id)

          date = forms.DateTimeField()
          firm = forms.ModelChoiceField(queryset=Firme.objects.all()) # why do you want a list of all firms here? Or do you want a single object?
          node_ids = forms.ModelMultipleChoiceField(queryset=Node.objects.none()), widget=forms.CheckboxSelectMultiple)

          class Meta:
          model = ScheduledAction
          fields = [
          'date',
          'firm',
          'node_ids'
          ]


          now for you view:



          def planification_view(request, id):
          firme = get_object_or_404(Firme, id=id)
          nodes = Node.objects.all()
          if request.method == 'POST':
          form = ScheduledActionForm(data=request.POST, firme=firme)
          if form.is_valid():
          scheduledAction = form.save()
          print('formulaire enregistre')
          else:
          form = ScheduledActionForm(firme=firme)

          context = {
          'firme': firme,
          'form': form,
          'nodes': nodes
          }
          return render(request, "node/planification.html", context)


          Something along these lines should get you going. It might still require some tweaking to get it to work in your project. If you still have trouble understanding please read the Django docs and or do their tutorial



          Update 2:
          Not the prettiest solution but it works for the OP






          share|improve this answer


























          • I'm new to Django, can you please explain your solution in detail? Thanks.

            – Tessnim
            Jan 2 at 10:20











          • can you show me the view you use to render the form?

            – Matt
            Jan 2 at 10:30











          • I updated my post and added my view function.

            – Tessnim
            Jan 2 at 10:33













          • I just updated my answer!

            – Matt
            Jan 2 at 10:57











          • I tried your code and got this error: NameError: name 'firme' is not defined

            – Tessnim
            Jan 2 at 11:33














          2












          2








          2







          There are several things wrong with your approach



          first of all: you assigned the variable 'firm' to a form field and then using that same variable to get an object from the db won't work in anyway. The variable 'firm' in Node.objects.get(firm_id=firm.id) should be a firm instance.



          second: queryset=Node.objects.get(firm_id=firm.id) won't work because Model.objects.get() will return an object not a query set.



          If you want to show all the nodes for a specific Firm you will need to pass the firm object (or id or other identifier) to the form by for example passing it through the get_form_kwargs() if you are using CBV and filtering by it Node.objects.filter(firm_id=firm.id)



          Update:
          Since you are using function based views there might be a more dry way to do this, but I'm only used to working with CBV so I'll try my best



          On the form we will declare a new variable called firme (we will pass this to the form in your view)



          class ScheduledActionForm(forms.ModelForm):

          def __init__(self, *args, **kwargs):
          self.firme = kwargs.pop('firme')
          super(ScheduledActionForm, self).__init__(*args, **kwargs)
          self.fields['node_ids'].queryset = Node.objects.filter(firm_id=self.firme.id)

          date = forms.DateTimeField()
          firm = forms.ModelChoiceField(queryset=Firme.objects.all()) # why do you want a list of all firms here? Or do you want a single object?
          node_ids = forms.ModelMultipleChoiceField(queryset=Node.objects.none()), widget=forms.CheckboxSelectMultiple)

          class Meta:
          model = ScheduledAction
          fields = [
          'date',
          'firm',
          'node_ids'
          ]


          now for you view:



          def planification_view(request, id):
          firme = get_object_or_404(Firme, id=id)
          nodes = Node.objects.all()
          if request.method == 'POST':
          form = ScheduledActionForm(data=request.POST, firme=firme)
          if form.is_valid():
          scheduledAction = form.save()
          print('formulaire enregistre')
          else:
          form = ScheduledActionForm(firme=firme)

          context = {
          'firme': firme,
          'form': form,
          'nodes': nodes
          }
          return render(request, "node/planification.html", context)


          Something along these lines should get you going. It might still require some tweaking to get it to work in your project. If you still have trouble understanding please read the Django docs and or do their tutorial



          Update 2:
          Not the prettiest solution but it works for the OP






          share|improve this answer















          There are several things wrong with your approach



          first of all: you assigned the variable 'firm' to a form field and then using that same variable to get an object from the db won't work in anyway. The variable 'firm' in Node.objects.get(firm_id=firm.id) should be a firm instance.



          second: queryset=Node.objects.get(firm_id=firm.id) won't work because Model.objects.get() will return an object not a query set.



          If you want to show all the nodes for a specific Firm you will need to pass the firm object (or id or other identifier) to the form by for example passing it through the get_form_kwargs() if you are using CBV and filtering by it Node.objects.filter(firm_id=firm.id)



          Update:
          Since you are using function based views there might be a more dry way to do this, but I'm only used to working with CBV so I'll try my best



          On the form we will declare a new variable called firme (we will pass this to the form in your view)



          class ScheduledActionForm(forms.ModelForm):

          def __init__(self, *args, **kwargs):
          self.firme = kwargs.pop('firme')
          super(ScheduledActionForm, self).__init__(*args, **kwargs)
          self.fields['node_ids'].queryset = Node.objects.filter(firm_id=self.firme.id)

          date = forms.DateTimeField()
          firm = forms.ModelChoiceField(queryset=Firme.objects.all()) # why do you want a list of all firms here? Or do you want a single object?
          node_ids = forms.ModelMultipleChoiceField(queryset=Node.objects.none()), widget=forms.CheckboxSelectMultiple)

          class Meta:
          model = ScheduledAction
          fields = [
          'date',
          'firm',
          'node_ids'
          ]


          now for you view:



          def planification_view(request, id):
          firme = get_object_or_404(Firme, id=id)
          nodes = Node.objects.all()
          if request.method == 'POST':
          form = ScheduledActionForm(data=request.POST, firme=firme)
          if form.is_valid():
          scheduledAction = form.save()
          print('formulaire enregistre')
          else:
          form = ScheduledActionForm(firme=firme)

          context = {
          'firme': firme,
          'form': form,
          'nodes': nodes
          }
          return render(request, "node/planification.html", context)


          Something along these lines should get you going. It might still require some tweaking to get it to work in your project. If you still have trouble understanding please read the Django docs and or do their tutorial



          Update 2:
          Not the prettiest solution but it works for the OP







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 2 at 13:55

























          answered Jan 2 at 10:15









          MattMatt

          1216




          1216













          • I'm new to Django, can you please explain your solution in detail? Thanks.

            – Tessnim
            Jan 2 at 10:20











          • can you show me the view you use to render the form?

            – Matt
            Jan 2 at 10:30











          • I updated my post and added my view function.

            – Tessnim
            Jan 2 at 10:33













          • I just updated my answer!

            – Matt
            Jan 2 at 10:57











          • I tried your code and got this error: NameError: name 'firme' is not defined

            – Tessnim
            Jan 2 at 11:33



















          • I'm new to Django, can you please explain your solution in detail? Thanks.

            – Tessnim
            Jan 2 at 10:20











          • can you show me the view you use to render the form?

            – Matt
            Jan 2 at 10:30











          • I updated my post and added my view function.

            – Tessnim
            Jan 2 at 10:33













          • I just updated my answer!

            – Matt
            Jan 2 at 10:57











          • I tried your code and got this error: NameError: name 'firme' is not defined

            – Tessnim
            Jan 2 at 11:33

















          I'm new to Django, can you please explain your solution in detail? Thanks.

          – Tessnim
          Jan 2 at 10:20





          I'm new to Django, can you please explain your solution in detail? Thanks.

          – Tessnim
          Jan 2 at 10:20













          can you show me the view you use to render the form?

          – Matt
          Jan 2 at 10:30





          can you show me the view you use to render the form?

          – Matt
          Jan 2 at 10:30













          I updated my post and added my view function.

          – Tessnim
          Jan 2 at 10:33







          I updated my post and added my view function.

          – Tessnim
          Jan 2 at 10:33















          I just updated my answer!

          – Matt
          Jan 2 at 10:57





          I just updated my answer!

          – Matt
          Jan 2 at 10:57













          I tried your code and got this error: NameError: name 'firme' is not defined

          – Tessnim
          Jan 2 at 11:33





          I tried your code and got this error: NameError: name 'firme' is not defined

          – Tessnim
          Jan 2 at 11:33




















          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%2f54004320%2fget-the-list-of-related-objects-in-django%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

          MongoDB - Not Authorized To Execute Command

          in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

          How to fix TextFormField cause rebuild widget in Flutter