A
A
AiratZa2019-11-08 08:10:46
Django
AiratZa, 2019-11-08 08:10:46

How to create a formset with predefined data?

Essence of the question: it is necessary to create a set of forms based on the questions from the models.
in fact, the questions should be predefined, I somehow pulled them into the templates in the form of a list, and made hiddeninput in the forms.
There is some uncertainty in this decision, but so far I do not know how to do it differently.
the main problem at the moment is that in the drop-down list of answers there are answers to all questions. I would like to make sure that the answer options correspond to the questions that I pull out into the template in the form of text.
Any help is appreciated, maybe someone has already encountered such a problem))
views.py

def testing(request, recrut_id):
    if recrut_id:
        class TestingForm(forms.Form):            
            recrut = forms.ModelChoiceField(queryset=RecrutInfo.objects.filter(), widget=forms.HiddenInput(attrs={'value':recrut_id}))
            questions = forms.ModelChoiceField(queryset=TestingQuestion.objects.all(), widget=forms.HiddenInput())
            answers = forms.ModelChoiceField(queryset=TestingAnswers.objects.all())
        

        TestingFormSet = formset_factory(form=TestingForm, min_num=TestingQuestion.objects.count(), extra=0)
        questions = [i for i in TestingQuestion.objects.all()]

        if request.method =='POST':
            fs = TestingFormSet(request.POST, initial=[{'questions': i } for i in TestingQuestion.objects.all().iterator()])
            if fs.is_valid():
                cds = fs.cleaned_data
                print(cds)
                for cd in cds:
                    recrut = cd ['recrut']
                    answers = cd ['answers']
                    questions = cd ['questions']
                    RecrutAnswer.objects.create(recrut=recrut, answers=answers, questions=questions)
                return redirect('recruiting:choosing_role')
        else:
            fs = TestingFormSet(initial=[{'questions': i } for i in TestingQuestion.objects.all().iterator()])

    context = {'questions': questions,  'formset': fs} #
    return render(request, 'recruiting/testing.html', context)

models.py
class TestingQuestion(models.Model):
    id = models.AutoField(primary_key=True)
    question_text = models.CharField(max_length=256, verbose_name='Текст вопроса')
    def isVote(self, user_id):
        if self.recrutanswer_set.filter(vote=True, user=user_id).count() > 0:
            return True
        else:
            return False
    def get_answers(self):
        return self.testinganswers_set.all()
    answers = property(get_answers)
    class Meta:
        verbose_name = 'Вопрос'
        verbose_name_plural = 'Вопросы'
    def __str__(self):
        return self.question_text


class TestingAnswers(models.Model):
    id = models.AutoField(primary_key=True)
    question = models.ForeignKey(TestingQuestion, on_delete=models.CASCADE, verbose_name='Вопрос', blank=True)
    answers = models.CharField(max_length=255,verbose_name='Ответы', null=False, blank=True)
    timestamp = models.DateTimeField(auto_now_add=True, null=True)

    def get_question_text(self):
        return self.question.question_text
    question_text = property(get_question_text)
    class Meta:
        verbose_name = 'Варианты ответов'
        verbose_name_plural = 'Варианты ответов'
    def __str__(self):
        return str(self.answers)

class RecrutAnswer(models.Model):
    id = models.AutoField(primary_key=True)
    recrut = models.ForeignKey(RecrutInfo, on_delete=models.CASCADE, unique=False)
    questions = models.ForeignKey(TestingQuestion, on_delete=models.PROTECT, unique=False, null=False)
    answers = models.ForeignKey(TestingAnswers, on_delete=models.PROTECT, unique=False, null=False)
    
    def get_question_text(self):
        return self.answers.question.question_text
    
    question_text = property(get_question_text)
    class Meta:
        verbose_name = 'Ответы пользователей'
        verbose_name_plural = 'Ответы пользователей'
    def __str__(self):
        return '%s %s' % (self.recrut, self.answers)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question