Passing Parameter for Queryset to Django Form












1















I am using a django (2.1) ModelMultipleChoice field for a form. I am trying to modify the queryset based on the slug in the URL. I am pretty certain I am missing something stupid.



The Form:



class SubdomainForm(forms.Form):
# TODO Get the value slug from init
slug = "camp" # Works well if value of slug set here.
q = Feature2Subdomain.objects.all().select_related().filter(subdomain__slug=slug)
choices = forms.ModelMultipleChoiceField(
queryset = q,
widget = forms.CheckboxSelectMultiple,
)

def __init__(self, *args, **kwargs):
slug = kwargs.pop('slug', None) # Correctly obtains slug from url
super(SubdomainForm, self).__init__(*args, **kwargs)


The View:



class SubdomainDetailView(FormView):
template_name = "guide/subdomain-detail.html"
form_class = SubdomainForm

def get_form_kwargs(self, form_class=SubdomainForm):
s = dict(slug = self.kwargs['slug'])
return s


URLS.py



urlpatterns = [
path('subdomain/<slug:slug>/',
SubdomainDetailView.as_view(),
name="subdomain-detail"
),
.....


Obviously, the idea is that the slug from the URL is used to modify the queryset. (in the example the value of the slug is "camp"



I can obtain the value of the slug in the init method for the form, and can call super() to instantiate the form. However, I can't figure out how to access the value in the "choices" line of the form. If I hard code the value of slug="camp" I can get the whole thing to work properly.



I've been working on this for a couple of days and have exhausted all the examples in SO and on google.



I tried moving the "choices" assignment into the init method and using



 self.choices = forms.ModelMultipleChoiceField(
queryset = Feature2Subdomain.objects.all().select_related().filter(subdomain__slug=slug)
widget = forms.CheckboxSelectMultiple,
)


But this is not then displaying the correct response (it returns an empty form)



Also tried assigning the queryset in the init method like this.



class SubdomainForm(forms.Form):
choices = forms.ModelMultipleChoiceField(
widget = forms.CheckboxSelectMultiple,
)

def __init__(self, *args, **kwargs):
slug = kwargs.pop('slug', None) # Correctly obtains slug from url
self.queryset = Feature2Subdomain.objects.all().select_related().filter(subdomain__slug=slug)

super(SubdomainForm, self).__init__(*args, **kwargs)


I then get the error:
TypeError: init() missing 1 required positional argument: 'queryset'



Feeling quite lost on where to go next.



Any help would be appreciate.










share|improve this question



























    1















    I am using a django (2.1) ModelMultipleChoice field for a form. I am trying to modify the queryset based on the slug in the URL. I am pretty certain I am missing something stupid.



    The Form:



    class SubdomainForm(forms.Form):
    # TODO Get the value slug from init
    slug = "camp" # Works well if value of slug set here.
    q = Feature2Subdomain.objects.all().select_related().filter(subdomain__slug=slug)
    choices = forms.ModelMultipleChoiceField(
    queryset = q,
    widget = forms.CheckboxSelectMultiple,
    )

    def __init__(self, *args, **kwargs):
    slug = kwargs.pop('slug', None) # Correctly obtains slug from url
    super(SubdomainForm, self).__init__(*args, **kwargs)


    The View:



    class SubdomainDetailView(FormView):
    template_name = "guide/subdomain-detail.html"
    form_class = SubdomainForm

    def get_form_kwargs(self, form_class=SubdomainForm):
    s = dict(slug = self.kwargs['slug'])
    return s


    URLS.py



    urlpatterns = [
    path('subdomain/<slug:slug>/',
    SubdomainDetailView.as_view(),
    name="subdomain-detail"
    ),
    .....


    Obviously, the idea is that the slug from the URL is used to modify the queryset. (in the example the value of the slug is "camp"



    I can obtain the value of the slug in the init method for the form, and can call super() to instantiate the form. However, I can't figure out how to access the value in the "choices" line of the form. If I hard code the value of slug="camp" I can get the whole thing to work properly.



    I've been working on this for a couple of days and have exhausted all the examples in SO and on google.



    I tried moving the "choices" assignment into the init method and using



     self.choices = forms.ModelMultipleChoiceField(
    queryset = Feature2Subdomain.objects.all().select_related().filter(subdomain__slug=slug)
    widget = forms.CheckboxSelectMultiple,
    )


    But this is not then displaying the correct response (it returns an empty form)



    Also tried assigning the queryset in the init method like this.



    class SubdomainForm(forms.Form):
    choices = forms.ModelMultipleChoiceField(
    widget = forms.CheckboxSelectMultiple,
    )

    def __init__(self, *args, **kwargs):
    slug = kwargs.pop('slug', None) # Correctly obtains slug from url
    self.queryset = Feature2Subdomain.objects.all().select_related().filter(subdomain__slug=slug)

    super(SubdomainForm, self).__init__(*args, **kwargs)


    I then get the error:
    TypeError: init() missing 1 required positional argument: 'queryset'



    Feeling quite lost on where to go next.



    Any help would be appreciate.










    share|improve this question

























      1












      1








      1








      I am using a django (2.1) ModelMultipleChoice field for a form. I am trying to modify the queryset based on the slug in the URL. I am pretty certain I am missing something stupid.



      The Form:



      class SubdomainForm(forms.Form):
      # TODO Get the value slug from init
      slug = "camp" # Works well if value of slug set here.
      q = Feature2Subdomain.objects.all().select_related().filter(subdomain__slug=slug)
      choices = forms.ModelMultipleChoiceField(
      queryset = q,
      widget = forms.CheckboxSelectMultiple,
      )

      def __init__(self, *args, **kwargs):
      slug = kwargs.pop('slug', None) # Correctly obtains slug from url
      super(SubdomainForm, self).__init__(*args, **kwargs)


      The View:



      class SubdomainDetailView(FormView):
      template_name = "guide/subdomain-detail.html"
      form_class = SubdomainForm

      def get_form_kwargs(self, form_class=SubdomainForm):
      s = dict(slug = self.kwargs['slug'])
      return s


      URLS.py



      urlpatterns = [
      path('subdomain/<slug:slug>/',
      SubdomainDetailView.as_view(),
      name="subdomain-detail"
      ),
      .....


      Obviously, the idea is that the slug from the URL is used to modify the queryset. (in the example the value of the slug is "camp"



      I can obtain the value of the slug in the init method for the form, and can call super() to instantiate the form. However, I can't figure out how to access the value in the "choices" line of the form. If I hard code the value of slug="camp" I can get the whole thing to work properly.



      I've been working on this for a couple of days and have exhausted all the examples in SO and on google.



      I tried moving the "choices" assignment into the init method and using



       self.choices = forms.ModelMultipleChoiceField(
      queryset = Feature2Subdomain.objects.all().select_related().filter(subdomain__slug=slug)
      widget = forms.CheckboxSelectMultiple,
      )


      But this is not then displaying the correct response (it returns an empty form)



      Also tried assigning the queryset in the init method like this.



      class SubdomainForm(forms.Form):
      choices = forms.ModelMultipleChoiceField(
      widget = forms.CheckboxSelectMultiple,
      )

      def __init__(self, *args, **kwargs):
      slug = kwargs.pop('slug', None) # Correctly obtains slug from url
      self.queryset = Feature2Subdomain.objects.all().select_related().filter(subdomain__slug=slug)

      super(SubdomainForm, self).__init__(*args, **kwargs)


      I then get the error:
      TypeError: init() missing 1 required positional argument: 'queryset'



      Feeling quite lost on where to go next.



      Any help would be appreciate.










      share|improve this question














      I am using a django (2.1) ModelMultipleChoice field for a form. I am trying to modify the queryset based on the slug in the URL. I am pretty certain I am missing something stupid.



      The Form:



      class SubdomainForm(forms.Form):
      # TODO Get the value slug from init
      slug = "camp" # Works well if value of slug set here.
      q = Feature2Subdomain.objects.all().select_related().filter(subdomain__slug=slug)
      choices = forms.ModelMultipleChoiceField(
      queryset = q,
      widget = forms.CheckboxSelectMultiple,
      )

      def __init__(self, *args, **kwargs):
      slug = kwargs.pop('slug', None) # Correctly obtains slug from url
      super(SubdomainForm, self).__init__(*args, **kwargs)


      The View:



      class SubdomainDetailView(FormView):
      template_name = "guide/subdomain-detail.html"
      form_class = SubdomainForm

      def get_form_kwargs(self, form_class=SubdomainForm):
      s = dict(slug = self.kwargs['slug'])
      return s


      URLS.py



      urlpatterns = [
      path('subdomain/<slug:slug>/',
      SubdomainDetailView.as_view(),
      name="subdomain-detail"
      ),
      .....


      Obviously, the idea is that the slug from the URL is used to modify the queryset. (in the example the value of the slug is "camp"



      I can obtain the value of the slug in the init method for the form, and can call super() to instantiate the form. However, I can't figure out how to access the value in the "choices" line of the form. If I hard code the value of slug="camp" I can get the whole thing to work properly.



      I've been working on this for a couple of days and have exhausted all the examples in SO and on google.



      I tried moving the "choices" assignment into the init method and using



       self.choices = forms.ModelMultipleChoiceField(
      queryset = Feature2Subdomain.objects.all().select_related().filter(subdomain__slug=slug)
      widget = forms.CheckboxSelectMultiple,
      )


      But this is not then displaying the correct response (it returns an empty form)



      Also tried assigning the queryset in the init method like this.



      class SubdomainForm(forms.Form):
      choices = forms.ModelMultipleChoiceField(
      widget = forms.CheckboxSelectMultiple,
      )

      def __init__(self, *args, **kwargs):
      slug = kwargs.pop('slug', None) # Correctly obtains slug from url
      self.queryset = Feature2Subdomain.objects.all().select_related().filter(subdomain__slug=slug)

      super(SubdomainForm, self).__init__(*args, **kwargs)


      I then get the error:
      TypeError: init() missing 1 required positional argument: 'queryset'



      Feeling quite lost on where to go next.



      Any help would be appreciate.







      django django-forms






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Dec 31 '18 at 15:27









      jeffrey.francjeffrey.franc

      82




      82
























          1 Answer
          1






          active

          oldest

          votes


















          0














          For your last attempt, you can modify the code like this:



          class SubdomainForm(forms.Form):
          choices = forms.ModelMultipleChoiceField(
          widget = forms.CheckboxSelectMultiple,
          queryset = Feature2Subdomain.objects.all()
          )

          def __init__(self, *args, **kwargs):
          slug = kwargs.pop('slug', None) # Correctly obtains slug from url
          self.fields['choices'].queryset = Feature2Subdomain.objects.filter(subdomain__slug=slug) # you don't need select related

          super(SubdomainForm, self).__init__(*args, **kwargs)





          share|improve this answer
























          • Got it. I need to declare a queryset in the form definition, but this is over-ridden by the init method.

            – jeffrey.franc
            Jan 2 at 15:10











          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%2f53989024%2fpassing-parameter-for-queryset-to-django-form%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









          0














          For your last attempt, you can modify the code like this:



          class SubdomainForm(forms.Form):
          choices = forms.ModelMultipleChoiceField(
          widget = forms.CheckboxSelectMultiple,
          queryset = Feature2Subdomain.objects.all()
          )

          def __init__(self, *args, **kwargs):
          slug = kwargs.pop('slug', None) # Correctly obtains slug from url
          self.fields['choices'].queryset = Feature2Subdomain.objects.filter(subdomain__slug=slug) # you don't need select related

          super(SubdomainForm, self).__init__(*args, **kwargs)





          share|improve this answer
























          • Got it. I need to declare a queryset in the form definition, but this is over-ridden by the init method.

            – jeffrey.franc
            Jan 2 at 15:10
















          0














          For your last attempt, you can modify the code like this:



          class SubdomainForm(forms.Form):
          choices = forms.ModelMultipleChoiceField(
          widget = forms.CheckboxSelectMultiple,
          queryset = Feature2Subdomain.objects.all()
          )

          def __init__(self, *args, **kwargs):
          slug = kwargs.pop('slug', None) # Correctly obtains slug from url
          self.fields['choices'].queryset = Feature2Subdomain.objects.filter(subdomain__slug=slug) # you don't need select related

          super(SubdomainForm, self).__init__(*args, **kwargs)





          share|improve this answer
























          • Got it. I need to declare a queryset in the form definition, but this is over-ridden by the init method.

            – jeffrey.franc
            Jan 2 at 15:10














          0












          0








          0







          For your last attempt, you can modify the code like this:



          class SubdomainForm(forms.Form):
          choices = forms.ModelMultipleChoiceField(
          widget = forms.CheckboxSelectMultiple,
          queryset = Feature2Subdomain.objects.all()
          )

          def __init__(self, *args, **kwargs):
          slug = kwargs.pop('slug', None) # Correctly obtains slug from url
          self.fields['choices'].queryset = Feature2Subdomain.objects.filter(subdomain__slug=slug) # you don't need select related

          super(SubdomainForm, self).__init__(*args, **kwargs)





          share|improve this answer













          For your last attempt, you can modify the code like this:



          class SubdomainForm(forms.Form):
          choices = forms.ModelMultipleChoiceField(
          widget = forms.CheckboxSelectMultiple,
          queryset = Feature2Subdomain.objects.all()
          )

          def __init__(self, *args, **kwargs):
          slug = kwargs.pop('slug', None) # Correctly obtains slug from url
          self.fields['choices'].queryset = Feature2Subdomain.objects.filter(subdomain__slug=slug) # you don't need select related

          super(SubdomainForm, self).__init__(*args, **kwargs)






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 1 at 6:14









          ruddraruddra

          15.2k32750




          15.2k32750













          • Got it. I need to declare a queryset in the form definition, but this is over-ridden by the init method.

            – jeffrey.franc
            Jan 2 at 15:10



















          • Got it. I need to declare a queryset in the form definition, but this is over-ridden by the init method.

            – jeffrey.franc
            Jan 2 at 15:10

















          Got it. I need to declare a queryset in the form definition, but this is over-ridden by the init method.

          – jeffrey.franc
          Jan 2 at 15:10





          Got it. I need to declare a queryset in the form definition, but this is over-ridden by the init method.

          – jeffrey.franc
          Jan 2 at 15:10




















          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%2f53989024%2fpassing-parameter-for-queryset-to-django-form%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

          How to fix TextFormField cause rebuild widget in Flutter

          Npm cannot find a required file even through it is in the searched directory