Answer the question
In order to leave comments, you need to log in
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
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.")
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)
__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>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question