Django: CreateView object with dynamic form fields not saved












0














I set up a working CreateView. However, when I made one of my modelform fields ('erlaubte_pruefer') dynamic, the object is not saved anymore.



I've tried many solutions suggested in other posts, e.g.
- get user variable in get_form_kwargs(),
- limit the field choices in get_form() instead of forms.py
- don't use CreateView



but I just can't make it work. I don't get an error or exception, the form is only rendered again.



I would highly appreciate your input. Thank you!



forms.py



class Checklisten_Reinigung_Form(forms.ModelForm):

class Meta:
model = Checklisten_Reinigung
fields = ['okay',
'raum_verbindung',
'ausfuehrer',
'erlaubte_pruefer'
]

# user should only choose from those objects that were created by himself
def __init__(self, user, *args, **kwargs):
super(Checklisten_Reinigung_Form, self).__init__(*args, **kwargs)
self.fields['erlaubte_pruefer'].queryset =
Pruefer.objects.filter(firmenzugehoerigkeit=user)


views.py



class Checklisten_Reinigung_Create_View(LoginRequiredMixin, CreateView):
template_name = 'checklisten/checklisten_form.html'

def get_context_data(self, **kwargs):
context = super(Checklisten_Reinigung_Create_View,
self).get_context_data(**kwargs)
context['mymodel'] = Checklisten_Reinigung()
return context

# if I leave out get_form() the object is successfully saved
# but the user's choice is not limited

def get_form(self, form_class=None):
form = Checklisten_Reinigung_Form(user=self.request.user)
return form

def form_valid(self, form):
self.object = form.save(commit=False)

try:
self.object.pruefende_firma = self.request.user
self.object.bezeichnung = self.object.bezeichnung
self.object.ausfuehrer = form.cleaned_data['ausfuehrer']
self.object.erlaubte_pruefer =
form.cleaned_data['erlaubte_pruefer']
self.object.okay = form.cleaned_data['okay']
self.object.raum_verbindung= form.cleaned_data['raum_verbindung']
self.object.save()


return HttpResponseRedirect(self.get_success_url())

except:
messages.error(self.request, 'Es ist ein Fehler aufgetreten.')
return self.render_to_response(self.get_context_data(form=form(user=self.request.user)))

def get_success_url(self):
messages.success(self.request, 'Checkliste erfolgreich gespeichert.')
return reverse('checkliste-startseite')


EDIT:



Thank you, @Daniel Rosemann for your reply. I included your code into mine but get this error:



Traceback:

File "C:UsersMarsAnaconda3libsite-packagesdjangocorehandlersexception.py" in inner
34. response = get_response(request)

File "C:UsersMarsAnaconda3libsite-packagesdjangocorehandlersbase.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)

File "C:UsersMarsAnaconda3libsite-packagesdjangocorehandlersbase.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericbase.py" in view
68. return self.dispatch(request, *args, **kwargs)

File "C:UsersMarsAnaconda3libsite-packagesdjangocontribauthmixins.py" in dispatch
52. return super().dispatch(request, *args, **kwargs)

File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericbase.py" in dispatch
88. return handler(request, *args, **kwargs)

File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get
168. return super().get(request, *args, **kwargs)

File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get
133. return self.render_to_response(self.get_context_data())

File "C:UsersMarsDesktopmorecooking_nowmorecooking_nowchecklistenviews.py" in get_context_data
372. context = super(Checklisten_Reinigung_Create_View, self).get_context_data(**kwargs)

File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get_context_data
66. kwargs['form'] = self.get_form()

File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get_form
32. form_class = self.get_form_class()

File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get_form_class
93. model = self.get_queryset().model

File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericdetail.py" in get_queryset
73. 'cls': self.__class__.__name__

Exception Type: ImproperlyConfigured at /checklisten/reinigung/neu/
Exception Value: Checklisten_Reinigung_Create_View is missing a QuerySet. Define Checklisten_Reinigung_Create_View.model, Checklisten_Reinigung_Create_View.queryset, or override Checklisten_Reinigung_Create_View.get_queryset().


Thank you again!










share|improve this question





























    0














    I set up a working CreateView. However, when I made one of my modelform fields ('erlaubte_pruefer') dynamic, the object is not saved anymore.



    I've tried many solutions suggested in other posts, e.g.
    - get user variable in get_form_kwargs(),
    - limit the field choices in get_form() instead of forms.py
    - don't use CreateView



    but I just can't make it work. I don't get an error or exception, the form is only rendered again.



    I would highly appreciate your input. Thank you!



    forms.py



    class Checklisten_Reinigung_Form(forms.ModelForm):

    class Meta:
    model = Checklisten_Reinigung
    fields = ['okay',
    'raum_verbindung',
    'ausfuehrer',
    'erlaubte_pruefer'
    ]

    # user should only choose from those objects that were created by himself
    def __init__(self, user, *args, **kwargs):
    super(Checklisten_Reinigung_Form, self).__init__(*args, **kwargs)
    self.fields['erlaubte_pruefer'].queryset =
    Pruefer.objects.filter(firmenzugehoerigkeit=user)


    views.py



    class Checklisten_Reinigung_Create_View(LoginRequiredMixin, CreateView):
    template_name = 'checklisten/checklisten_form.html'

    def get_context_data(self, **kwargs):
    context = super(Checklisten_Reinigung_Create_View,
    self).get_context_data(**kwargs)
    context['mymodel'] = Checklisten_Reinigung()
    return context

    # if I leave out get_form() the object is successfully saved
    # but the user's choice is not limited

    def get_form(self, form_class=None):
    form = Checklisten_Reinigung_Form(user=self.request.user)
    return form

    def form_valid(self, form):
    self.object = form.save(commit=False)

    try:
    self.object.pruefende_firma = self.request.user
    self.object.bezeichnung = self.object.bezeichnung
    self.object.ausfuehrer = form.cleaned_data['ausfuehrer']
    self.object.erlaubte_pruefer =
    form.cleaned_data['erlaubte_pruefer']
    self.object.okay = form.cleaned_data['okay']
    self.object.raum_verbindung= form.cleaned_data['raum_verbindung']
    self.object.save()


    return HttpResponseRedirect(self.get_success_url())

    except:
    messages.error(self.request, 'Es ist ein Fehler aufgetreten.')
    return self.render_to_response(self.get_context_data(form=form(user=self.request.user)))

    def get_success_url(self):
    messages.success(self.request, 'Checkliste erfolgreich gespeichert.')
    return reverse('checkliste-startseite')


    EDIT:



    Thank you, @Daniel Rosemann for your reply. I included your code into mine but get this error:



    Traceback:

    File "C:UsersMarsAnaconda3libsite-packagesdjangocorehandlersexception.py" in inner
    34. response = get_response(request)

    File "C:UsersMarsAnaconda3libsite-packagesdjangocorehandlersbase.py" in _get_response
    126. response = self.process_exception_by_middleware(e, request)

    File "C:UsersMarsAnaconda3libsite-packagesdjangocorehandlersbase.py" in _get_response
    124. response = wrapped_callback(request, *callback_args, **callback_kwargs)

    File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericbase.py" in view
    68. return self.dispatch(request, *args, **kwargs)

    File "C:UsersMarsAnaconda3libsite-packagesdjangocontribauthmixins.py" in dispatch
    52. return super().dispatch(request, *args, **kwargs)

    File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericbase.py" in dispatch
    88. return handler(request, *args, **kwargs)

    File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get
    168. return super().get(request, *args, **kwargs)

    File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get
    133. return self.render_to_response(self.get_context_data())

    File "C:UsersMarsDesktopmorecooking_nowmorecooking_nowchecklistenviews.py" in get_context_data
    372. context = super(Checklisten_Reinigung_Create_View, self).get_context_data(**kwargs)

    File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get_context_data
    66. kwargs['form'] = self.get_form()

    File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get_form
    32. form_class = self.get_form_class()

    File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get_form_class
    93. model = self.get_queryset().model

    File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericdetail.py" in get_queryset
    73. 'cls': self.__class__.__name__

    Exception Type: ImproperlyConfigured at /checklisten/reinigung/neu/
    Exception Value: Checklisten_Reinigung_Create_View is missing a QuerySet. Define Checklisten_Reinigung_Create_View.model, Checklisten_Reinigung_Create_View.queryset, or override Checklisten_Reinigung_Create_View.get_queryset().


    Thank you again!










    share|improve this question



























      0












      0








      0







      I set up a working CreateView. However, when I made one of my modelform fields ('erlaubte_pruefer') dynamic, the object is not saved anymore.



      I've tried many solutions suggested in other posts, e.g.
      - get user variable in get_form_kwargs(),
      - limit the field choices in get_form() instead of forms.py
      - don't use CreateView



      but I just can't make it work. I don't get an error or exception, the form is only rendered again.



      I would highly appreciate your input. Thank you!



      forms.py



      class Checklisten_Reinigung_Form(forms.ModelForm):

      class Meta:
      model = Checklisten_Reinigung
      fields = ['okay',
      'raum_verbindung',
      'ausfuehrer',
      'erlaubte_pruefer'
      ]

      # user should only choose from those objects that were created by himself
      def __init__(self, user, *args, **kwargs):
      super(Checklisten_Reinigung_Form, self).__init__(*args, **kwargs)
      self.fields['erlaubte_pruefer'].queryset =
      Pruefer.objects.filter(firmenzugehoerigkeit=user)


      views.py



      class Checklisten_Reinigung_Create_View(LoginRequiredMixin, CreateView):
      template_name = 'checklisten/checklisten_form.html'

      def get_context_data(self, **kwargs):
      context = super(Checklisten_Reinigung_Create_View,
      self).get_context_data(**kwargs)
      context['mymodel'] = Checklisten_Reinigung()
      return context

      # if I leave out get_form() the object is successfully saved
      # but the user's choice is not limited

      def get_form(self, form_class=None):
      form = Checklisten_Reinigung_Form(user=self.request.user)
      return form

      def form_valid(self, form):
      self.object = form.save(commit=False)

      try:
      self.object.pruefende_firma = self.request.user
      self.object.bezeichnung = self.object.bezeichnung
      self.object.ausfuehrer = form.cleaned_data['ausfuehrer']
      self.object.erlaubte_pruefer =
      form.cleaned_data['erlaubte_pruefer']
      self.object.okay = form.cleaned_data['okay']
      self.object.raum_verbindung= form.cleaned_data['raum_verbindung']
      self.object.save()


      return HttpResponseRedirect(self.get_success_url())

      except:
      messages.error(self.request, 'Es ist ein Fehler aufgetreten.')
      return self.render_to_response(self.get_context_data(form=form(user=self.request.user)))

      def get_success_url(self):
      messages.success(self.request, 'Checkliste erfolgreich gespeichert.')
      return reverse('checkliste-startseite')


      EDIT:



      Thank you, @Daniel Rosemann for your reply. I included your code into mine but get this error:



      Traceback:

      File "C:UsersMarsAnaconda3libsite-packagesdjangocorehandlersexception.py" in inner
      34. response = get_response(request)

      File "C:UsersMarsAnaconda3libsite-packagesdjangocorehandlersbase.py" in _get_response
      126. response = self.process_exception_by_middleware(e, request)

      File "C:UsersMarsAnaconda3libsite-packagesdjangocorehandlersbase.py" in _get_response
      124. response = wrapped_callback(request, *callback_args, **callback_kwargs)

      File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericbase.py" in view
      68. return self.dispatch(request, *args, **kwargs)

      File "C:UsersMarsAnaconda3libsite-packagesdjangocontribauthmixins.py" in dispatch
      52. return super().dispatch(request, *args, **kwargs)

      File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericbase.py" in dispatch
      88. return handler(request, *args, **kwargs)

      File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get
      168. return super().get(request, *args, **kwargs)

      File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get
      133. return self.render_to_response(self.get_context_data())

      File "C:UsersMarsDesktopmorecooking_nowmorecooking_nowchecklistenviews.py" in get_context_data
      372. context = super(Checklisten_Reinigung_Create_View, self).get_context_data(**kwargs)

      File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get_context_data
      66. kwargs['form'] = self.get_form()

      File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get_form
      32. form_class = self.get_form_class()

      File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get_form_class
      93. model = self.get_queryset().model

      File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericdetail.py" in get_queryset
      73. 'cls': self.__class__.__name__

      Exception Type: ImproperlyConfigured at /checklisten/reinigung/neu/
      Exception Value: Checklisten_Reinigung_Create_View is missing a QuerySet. Define Checklisten_Reinigung_Create_View.model, Checklisten_Reinigung_Create_View.queryset, or override Checklisten_Reinigung_Create_View.get_queryset().


      Thank you again!










      share|improve this question















      I set up a working CreateView. However, when I made one of my modelform fields ('erlaubte_pruefer') dynamic, the object is not saved anymore.



      I've tried many solutions suggested in other posts, e.g.
      - get user variable in get_form_kwargs(),
      - limit the field choices in get_form() instead of forms.py
      - don't use CreateView



      but I just can't make it work. I don't get an error or exception, the form is only rendered again.



      I would highly appreciate your input. Thank you!



      forms.py



      class Checklisten_Reinigung_Form(forms.ModelForm):

      class Meta:
      model = Checklisten_Reinigung
      fields = ['okay',
      'raum_verbindung',
      'ausfuehrer',
      'erlaubte_pruefer'
      ]

      # user should only choose from those objects that were created by himself
      def __init__(self, user, *args, **kwargs):
      super(Checklisten_Reinigung_Form, self).__init__(*args, **kwargs)
      self.fields['erlaubte_pruefer'].queryset =
      Pruefer.objects.filter(firmenzugehoerigkeit=user)


      views.py



      class Checklisten_Reinigung_Create_View(LoginRequiredMixin, CreateView):
      template_name = 'checklisten/checklisten_form.html'

      def get_context_data(self, **kwargs):
      context = super(Checklisten_Reinigung_Create_View,
      self).get_context_data(**kwargs)
      context['mymodel'] = Checklisten_Reinigung()
      return context

      # if I leave out get_form() the object is successfully saved
      # but the user's choice is not limited

      def get_form(self, form_class=None):
      form = Checklisten_Reinigung_Form(user=self.request.user)
      return form

      def form_valid(self, form):
      self.object = form.save(commit=False)

      try:
      self.object.pruefende_firma = self.request.user
      self.object.bezeichnung = self.object.bezeichnung
      self.object.ausfuehrer = form.cleaned_data['ausfuehrer']
      self.object.erlaubte_pruefer =
      form.cleaned_data['erlaubte_pruefer']
      self.object.okay = form.cleaned_data['okay']
      self.object.raum_verbindung= form.cleaned_data['raum_verbindung']
      self.object.save()


      return HttpResponseRedirect(self.get_success_url())

      except:
      messages.error(self.request, 'Es ist ein Fehler aufgetreten.')
      return self.render_to_response(self.get_context_data(form=form(user=self.request.user)))

      def get_success_url(self):
      messages.success(self.request, 'Checkliste erfolgreich gespeichert.')
      return reverse('checkliste-startseite')


      EDIT:



      Thank you, @Daniel Rosemann for your reply. I included your code into mine but get this error:



      Traceback:

      File "C:UsersMarsAnaconda3libsite-packagesdjangocorehandlersexception.py" in inner
      34. response = get_response(request)

      File "C:UsersMarsAnaconda3libsite-packagesdjangocorehandlersbase.py" in _get_response
      126. response = self.process_exception_by_middleware(e, request)

      File "C:UsersMarsAnaconda3libsite-packagesdjangocorehandlersbase.py" in _get_response
      124. response = wrapped_callback(request, *callback_args, **callback_kwargs)

      File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericbase.py" in view
      68. return self.dispatch(request, *args, **kwargs)

      File "C:UsersMarsAnaconda3libsite-packagesdjangocontribauthmixins.py" in dispatch
      52. return super().dispatch(request, *args, **kwargs)

      File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericbase.py" in dispatch
      88. return handler(request, *args, **kwargs)

      File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get
      168. return super().get(request, *args, **kwargs)

      File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get
      133. return self.render_to_response(self.get_context_data())

      File "C:UsersMarsDesktopmorecooking_nowmorecooking_nowchecklistenviews.py" in get_context_data
      372. context = super(Checklisten_Reinigung_Create_View, self).get_context_data(**kwargs)

      File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get_context_data
      66. kwargs['form'] = self.get_form()

      File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get_form
      32. form_class = self.get_form_class()

      File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericedit.py" in get_form_class
      93. model = self.get_queryset().model

      File "C:UsersMarsAnaconda3libsite-packagesdjangoviewsgenericdetail.py" in get_queryset
      73. 'cls': self.__class__.__name__

      Exception Type: ImproperlyConfigured at /checklisten/reinigung/neu/
      Exception Value: Checklisten_Reinigung_Create_View is missing a QuerySet. Define Checklisten_Reinigung_Create_View.model, Checklisten_Reinigung_Create_View.queryset, or override Checklisten_Reinigung_Create_View.get_queryset().


      Thank you again!







      python django django-forms create-view






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 '18 at 16:03







      Katharina

















      asked Nov 21 '18 at 13:19









      Katharina Katharina

      104




      104
























          1 Answer
          1






          active

          oldest

          votes


















          0














          You have changed the signature of the form so that the first positional argument is now user, not data. But you've defined get_form to only ever pass user, and never data; so the form never gets any data and therefore can never be valid.



          Make user a kwarg instead:



          def __init__(self, *args, **kwargs):   # no user here
          user = kwargs.pop('user', None)
          super(Checklisten_Reinigung_Form, self).__init__(*args, **kwargs)
          self.fields['erlaubte_pruefer'].queryset =
          Pruefer.objects.filter(firmenzugehoerigkeit=user)


          and in the view, remove your definition of get_form and instead define get_form_kwargs to pass the user:



          def get_form_kwargs(self):
          kwargs = super().get_form_kwargs()
          kwargs['user'] = self.request.user
          return kwargs


          Note also, you're doing too much work in form_valid; the call to form.save will already have set the fields in the form, such as "erlaubte_pruefer" and "okay", so you don't need to set them manually.



          (And finally, it is absolutely no use at all to blindly catch all errors and just return a vague "an error has occurred" message. That hides the logging that will tell you what happened, and doesn't give the user any useful information. Only catch the errors you know you will deal with; remove that try/except and let Django show the default error page.)






          share|improve this answer























          • Rosemann, thanks a lot for your answer and the helpful tips - I now understand better. However, I now get the error: ImproperlyConfigured - Checklisten_Reinigung_Create_View is missing a QuerySet. Any thoughts?
            – Katharina
            Nov 21 '18 at 14:53












          • That's weird, that is a message from ListView or CreateView. Can you post the full traceback (as an edit to the question)?
            – Daniel Roseman
            Nov 21 '18 at 15:31










          • Rosemann Stupid me had a typo in the form that caused the error... Thank you, your solution worked fine!
            – Katharina
            Nov 25 '18 at 8:53











          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%2f53412962%2fdjango-createview-object-with-dynamic-form-fields-not-saved%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














          You have changed the signature of the form so that the first positional argument is now user, not data. But you've defined get_form to only ever pass user, and never data; so the form never gets any data and therefore can never be valid.



          Make user a kwarg instead:



          def __init__(self, *args, **kwargs):   # no user here
          user = kwargs.pop('user', None)
          super(Checklisten_Reinigung_Form, self).__init__(*args, **kwargs)
          self.fields['erlaubte_pruefer'].queryset =
          Pruefer.objects.filter(firmenzugehoerigkeit=user)


          and in the view, remove your definition of get_form and instead define get_form_kwargs to pass the user:



          def get_form_kwargs(self):
          kwargs = super().get_form_kwargs()
          kwargs['user'] = self.request.user
          return kwargs


          Note also, you're doing too much work in form_valid; the call to form.save will already have set the fields in the form, such as "erlaubte_pruefer" and "okay", so you don't need to set them manually.



          (And finally, it is absolutely no use at all to blindly catch all errors and just return a vague "an error has occurred" message. That hides the logging that will tell you what happened, and doesn't give the user any useful information. Only catch the errors you know you will deal with; remove that try/except and let Django show the default error page.)






          share|improve this answer























          • Rosemann, thanks a lot for your answer and the helpful tips - I now understand better. However, I now get the error: ImproperlyConfigured - Checklisten_Reinigung_Create_View is missing a QuerySet. Any thoughts?
            – Katharina
            Nov 21 '18 at 14:53












          • That's weird, that is a message from ListView or CreateView. Can you post the full traceback (as an edit to the question)?
            – Daniel Roseman
            Nov 21 '18 at 15:31










          • Rosemann Stupid me had a typo in the form that caused the error... Thank you, your solution worked fine!
            – Katharina
            Nov 25 '18 at 8:53
















          0














          You have changed the signature of the form so that the first positional argument is now user, not data. But you've defined get_form to only ever pass user, and never data; so the form never gets any data and therefore can never be valid.



          Make user a kwarg instead:



          def __init__(self, *args, **kwargs):   # no user here
          user = kwargs.pop('user', None)
          super(Checklisten_Reinigung_Form, self).__init__(*args, **kwargs)
          self.fields['erlaubte_pruefer'].queryset =
          Pruefer.objects.filter(firmenzugehoerigkeit=user)


          and in the view, remove your definition of get_form and instead define get_form_kwargs to pass the user:



          def get_form_kwargs(self):
          kwargs = super().get_form_kwargs()
          kwargs['user'] = self.request.user
          return kwargs


          Note also, you're doing too much work in form_valid; the call to form.save will already have set the fields in the form, such as "erlaubte_pruefer" and "okay", so you don't need to set them manually.



          (And finally, it is absolutely no use at all to blindly catch all errors and just return a vague "an error has occurred" message. That hides the logging that will tell you what happened, and doesn't give the user any useful information. Only catch the errors you know you will deal with; remove that try/except and let Django show the default error page.)






          share|improve this answer























          • Rosemann, thanks a lot for your answer and the helpful tips - I now understand better. However, I now get the error: ImproperlyConfigured - Checklisten_Reinigung_Create_View is missing a QuerySet. Any thoughts?
            – Katharina
            Nov 21 '18 at 14:53












          • That's weird, that is a message from ListView or CreateView. Can you post the full traceback (as an edit to the question)?
            – Daniel Roseman
            Nov 21 '18 at 15:31










          • Rosemann Stupid me had a typo in the form that caused the error... Thank you, your solution worked fine!
            – Katharina
            Nov 25 '18 at 8:53














          0












          0








          0






          You have changed the signature of the form so that the first positional argument is now user, not data. But you've defined get_form to only ever pass user, and never data; so the form never gets any data and therefore can never be valid.



          Make user a kwarg instead:



          def __init__(self, *args, **kwargs):   # no user here
          user = kwargs.pop('user', None)
          super(Checklisten_Reinigung_Form, self).__init__(*args, **kwargs)
          self.fields['erlaubte_pruefer'].queryset =
          Pruefer.objects.filter(firmenzugehoerigkeit=user)


          and in the view, remove your definition of get_form and instead define get_form_kwargs to pass the user:



          def get_form_kwargs(self):
          kwargs = super().get_form_kwargs()
          kwargs['user'] = self.request.user
          return kwargs


          Note also, you're doing too much work in form_valid; the call to form.save will already have set the fields in the form, such as "erlaubte_pruefer" and "okay", so you don't need to set them manually.



          (And finally, it is absolutely no use at all to blindly catch all errors and just return a vague "an error has occurred" message. That hides the logging that will tell you what happened, and doesn't give the user any useful information. Only catch the errors you know you will deal with; remove that try/except and let Django show the default error page.)






          share|improve this answer














          You have changed the signature of the form so that the first positional argument is now user, not data. But you've defined get_form to only ever pass user, and never data; so the form never gets any data and therefore can never be valid.



          Make user a kwarg instead:



          def __init__(self, *args, **kwargs):   # no user here
          user = kwargs.pop('user', None)
          super(Checklisten_Reinigung_Form, self).__init__(*args, **kwargs)
          self.fields['erlaubte_pruefer'].queryset =
          Pruefer.objects.filter(firmenzugehoerigkeit=user)


          and in the view, remove your definition of get_form and instead define get_form_kwargs to pass the user:



          def get_form_kwargs(self):
          kwargs = super().get_form_kwargs()
          kwargs['user'] = self.request.user
          return kwargs


          Note also, you're doing too much work in form_valid; the call to form.save will already have set the fields in the form, such as "erlaubte_pruefer" and "okay", so you don't need to set them manually.



          (And finally, it is absolutely no use at all to blindly catch all errors and just return a vague "an error has occurred" message. That hides the logging that will tell you what happened, and doesn't give the user any useful information. Only catch the errors you know you will deal with; remove that try/except and let Django show the default error page.)







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 21 '18 at 14:31

























          answered Nov 21 '18 at 14:23









          Daniel RosemanDaniel Roseman

          445k41576632




          445k41576632












          • Rosemann, thanks a lot for your answer and the helpful tips - I now understand better. However, I now get the error: ImproperlyConfigured - Checklisten_Reinigung_Create_View is missing a QuerySet. Any thoughts?
            – Katharina
            Nov 21 '18 at 14:53












          • That's weird, that is a message from ListView or CreateView. Can you post the full traceback (as an edit to the question)?
            – Daniel Roseman
            Nov 21 '18 at 15:31










          • Rosemann Stupid me had a typo in the form that caused the error... Thank you, your solution worked fine!
            – Katharina
            Nov 25 '18 at 8:53


















          • Rosemann, thanks a lot for your answer and the helpful tips - I now understand better. However, I now get the error: ImproperlyConfigured - Checklisten_Reinigung_Create_View is missing a QuerySet. Any thoughts?
            – Katharina
            Nov 21 '18 at 14:53












          • That's weird, that is a message from ListView or CreateView. Can you post the full traceback (as an edit to the question)?
            – Daniel Roseman
            Nov 21 '18 at 15:31










          • Rosemann Stupid me had a typo in the form that caused the error... Thank you, your solution worked fine!
            – Katharina
            Nov 25 '18 at 8:53
















          Rosemann, thanks a lot for your answer and the helpful tips - I now understand better. However, I now get the error: ImproperlyConfigured - Checklisten_Reinigung_Create_View is missing a QuerySet. Any thoughts?
          – Katharina
          Nov 21 '18 at 14:53






          Rosemann, thanks a lot for your answer and the helpful tips - I now understand better. However, I now get the error: ImproperlyConfigured - Checklisten_Reinigung_Create_View is missing a QuerySet. Any thoughts?
          – Katharina
          Nov 21 '18 at 14:53














          That's weird, that is a message from ListView or CreateView. Can you post the full traceback (as an edit to the question)?
          – Daniel Roseman
          Nov 21 '18 at 15:31




          That's weird, that is a message from ListView or CreateView. Can you post the full traceback (as an edit to the question)?
          – Daniel Roseman
          Nov 21 '18 at 15:31












          Rosemann Stupid me had a typo in the form that caused the error... Thank you, your solution worked fine!
          – Katharina
          Nov 25 '18 at 8:53




          Rosemann Stupid me had a typo in the form that caused the error... Thank you, your solution worked fine!
          – Katharina
          Nov 25 '18 at 8:53


















          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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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%2f53412962%2fdjango-createview-object-with-dynamic-form-fields-not-saved%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

          To store a contact into the json file from server.js file using a class in NodeJS

          Redirect URL with Chrome Remote Debugging Android Devices

          Dieringhausen