Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeError: __init__() got an unexpected keyword argument 'bot_id' when i pass a variable from views to form

I need to pass a variable from views to form to limit the selection of objects in the ModelChoiceField depending on the bot_id Tell me how to do it right, in the current implementation, the code gives an error TypeError: init() got an unexpected keyword argument ‘bot_id’.
My code:

views.py

def edit_question(request, bot_id, question_id):
    bot = get_object_or_404(SettingsBot, id=bot_id)
    question = get_object_or_404(Questions, id=question_id)
    QuestionInlineFormSet = inlineformset_factory(Questions, RelationQuestion, exclude=('bot',), fk_name='base', form=SubQuestionForm)
    if request.method == "POST":
        form = QuestionsForm(data=request.POST, instance=question)
        formset = QuestionInlineFormSet(request.POST, request.FILES, bot_id=bot_id, instance=question)
        if formset.is_valid():
            formset.save()
            return redirect(question.get_absolute_url())
    else:
        form = QuestionsForm(instance=question)
        formset = QuestionInlineFormSet(bot_id=bot_id, instance=question)
    return render(request, 'FAQ/edit_questions.html', {'question': question,
                                                   'bot': bot,
                                                   'form': form,
                                                   'formset': formset})

forms.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class SubQuestionForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.bot_id = kwargs.pop('bot_id', None)
        super(SubQuestionForm, self).__init__(*args, **kwargs)
        self.fields['sub'] = forms.ModelChoiceField(Questions.objects.filter(bot=self.bot_id))

    class Meta:
        model = RelationQuestion
        fields = ['sub']

models.py

class Questions(models.Model):
    question = models.CharField(max_length=30, verbose_name="Вопрос")
    answer = models.TextField(default="No text", verbose_name="Ответ на вопрос")
    id = models.BigAutoField(primary_key=True)
    bot = models.ForeignKey("SettingsBot", related_name="Бот", on_delete=models.CASCADE,
                        verbose_name="Бот")
    general = models.BooleanField(default=False, verbose_name="Отображать на стартовой странице")
    created = models.DateTimeField(auto_now_add=True, verbose_name="Создан")
    updated = models.DateTimeField(auto_now=True, db_index=True, verbose_name="Изменен")

    class Meta:
        verbose_name = "Вопрос"
        verbose_name_plural = "Вопросы"
        ordering = ('-id',)

    def get_absolute_url(self):
        return reverse('FAQ:edit_questions', kwargs={'question_id': str(self.id),
                                                 'bot_id': str(self.bot)})

    def __str__(self):
        return self.question

    def data(self):
        return [self.question, self.answer, self.id, self.general]

class RelationQuestion(models.Model):
    base = models.ForeignKey("Questions", related_name='Основной_вопрос', on_delete=models.CASCADE, verbose_name="Основной вопрос")
    sub = models.ForeignKey("Questions", related_name='Дополнительный_вопрос', on_delete=models.CASCADE, verbose_name="Дополнительный вопрос")
    created = models.DateTimeField(auto_now_add=True, verbose_name="Создан")
    updated = models.DateTimeField(auto_now=True, db_index=True, verbose_name="Изменен")

    class Meta:
        verbose_name = "Таблица связей вопросов"
        verbose_name_plural = "Таблица связей вопросов"
        unique_together = (("base", "sub"),)

edit_questions.html

    <form method="post">
        {{ form }}
        {{ formset.management_form }}
        <table>
            {% for form in formset %}
                {{ form }}
            {% endfor %}
        </table>
         {% csrf_token %}
        <input type="submit" value="Сохранить">
    </form>

Traceback

Traceback (most recent call last):
File "/home/user/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/user/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/user/.local/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/media/sf_Projects/AdminForFAQ/FAQ/views.py", line 40, in edit_question
formset = QuestionInlineFormSet(bot_id=3, instance=question)
File "/home/user/.local/lib/python3.8/site-packages/django/forms/models.py", line 915, in __init__
super().__init__(data, files, prefix=prefix, queryset=qs, **kwargs)
File "/home/user/.local/lib/python3.8/site-packages/django/forms/models.py", line 581, in __init__
super().__init__(**{'data': data, 'files': files, 'auto_id': auto_id, 'prefix': prefix, **kwargs})
TypeError: __init__() got an unexpected keyword argument 'bot_id'
[28/Jan/2022 18:55:15] "GET /FAQ/3/edit_questions/6 HTTP/1.1" 500 84370

>Solution :

You pass this as form_kwargs=… parameter [Django-doc], so:

formset = QuestionInlineFormSet(request.POST, request.FILES, form_kwargs={'bot_id': bot_id}, instance=question)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading