N
N
Neoliz2016-09-14 13:53:36
Django
Neoliz, 2016-09-14 13:53:36

How to define your BaseModelFormSet in django admin?

Good day. Please do not immediately throw tomatoes. Docks read, but to see something incomplete.
To business. There is a code. In the admin panel, when you open the edit or add page, an exception pops up.
python: 3.4.3
django 1.10
models.py

class Question(models.Model):
    question = models.TextField("Вопрос:")

    def __str__(self):
        return self.question


class Answers(models.Model):
    question = models.ForeignKey(Question, verbose_name="Вопрос: ")
    answer = models.CharField("Ответ:", max_length=250)
    correctly = models.BooleanField("Правильный ответ", default=False)

    def __str__(self):
        return self.answer

forms.py
from django import forms
from django.forms.models import BaseModelFormSet

from .models import Answers


class BaseCreateAnswersFormset(BaseModelFormSet):
    def clean(self):
        """Checks that no two answers have the same title."""
        if any(self.errors):
            return
        # super(BaseCreateAnswersFormset, self).clean()
        currently = False
        answers = []
        for form in self.forms:
            answer = form.cleaned_data['answer']
            if answer in answers:
                raise forms.ValidationError("Answers must be different.")
            if form.cleaned_data['correctly']:
                currently = True
            answers.append(answer)
        if not currently:
            raise forms.ValidationError("At least one answer must be correct.")

admin.py
from django.contrib import admin
from django.forms.models import modelformset_factory

from .models import Question, Answers
from .forms import BaseCreateAnswersFormset


class AnswerInline(admin.StackedInline):
    model = Answers
    extra = 3
    max_num = 3
    formset = modelformset_factory(model=Answers,
                                   fields="__all__",
                                   formset=BaseCreateAnswersFormset)


class QuestionAdmin(admin.ModelAdmin):
    inlines = [AnswerInline]


admin.site.register(Question, QuestionAdmin)

From the traceback, I only throw the main one:
TypeError at /admin/tests/question/add/
__init__() got an unexpected keyword argument 'instance'
The error is here: /home/nxexox/projects/cardio/venv/lib/python3.4/site- packages/django/forms/models.py in __init__, line 563
Here is the data that is there:
__class__: <class 'django.forms.models.BaseModelFormSet'>
auto_id: 'id_%s'
data: None
defaults:
{'auto_id': 'id_%s',
 'data': None,
 'files': None,
 'instance': <Question: >,
 'prefix': 'form'}
files: None
kwargs: {'instance': <Question: >}
prefix: 'form'
queryset: <QuerySet []>
self: <django.forms.formsets.AnswersFormFormSet object at 0x7f5089b6c748>

I'll post the full one if needed.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Neoliz, 2016-09-14
@timofeydeys

Question removed. It is necessary to inherit BaseInlineFormSet together with BaseModelFormSet

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question