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

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

我需要将一个变量从视图传递到表单以限制 ModelChoiceField 中对象的选择,具体取决于 bot_id 请告诉我如何正确执行,在当前的实现中,代码给出了一个错误类型错误:init() 得到了一个意外的关键字参数 'bot_id'。 我的代码:

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

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 (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

您将其作为 form_kwargs=… parameter [Django-doc] 传递,因此:

formset = QuestionInlineFormSet(request.POST, request.FILES, <strong>form_kwargs={'bot_id': bot_id}</strong>, instance=question)