Pass view arguments to Django form

Asked

Viewed 593 times

1

Hello, good night!

I’m doing a question and answer application on Jango and I have basically these models:

Multiple choice app:

class MCQuestao(Questao):

    def checar_correta(self, ans):
        answer = Alternativa.objects.get(id=ans)

        if answer.correta is True:
            return True
        else:
            return False

    def pegar_questoes(self):
        return Alternativa.objects.filter(questao=self)

    class Meta:
        verbose_name = 'Questão múltipla escolha'
        verbose_name_plural = 'Questões múltiplas escolhas'

class Alternativa(models.Model):
    questao = models.ForeignKey(MCQuestao, on_delete=models.CASCADE)
    resposta = models.TextField()
    fundteorico = models.TextField()
    correta = models.BooleanField(default=False)

    def __str__(self):
        return self.resposta

    class Meta:
        verbose_name = "Alternativa"
        verbose_name_plural = "Alternativas"

Question app:

class Situacao(models.Model):
    enunciado = models.TextField(max_length=2000, blank=True)
    certificado = models.ManyToManyField(Certificado)

    def __str__(self):
        return '{}...'.format(self.enunciado[:80])

    def get_resolucao(self):
        return self.resolucao

    class Meta:
        verbose_name = "Situação" 
        verbose_name_plural = "Situações"

class Resolucao(models.Model):
    resolucao = models.TextField(max_length=1000, blank=True)
    situacao = models.OneToOneField(Situacao, on_delete=models.CASCADE)

    def __str__(self):
        return self.resolucao

    class Meta:
        verbose_name = "Resolução"
        verbose_name_plural = "Situações"

class Questao(models.Model):
    subdominio = models.ManyToManyField(SubDominio)
    resolucao = models.ForeignKey(Resolucao, on_delete=models.CASCADE, default='')
    questao = models.TextField(max_length=1000, blank=True)

    def __str__(self):
        return self.questao

    objects = InheritanceManager()

    class Meta:
        verbose_name = "Questão"
        verbose_name_plural = "Questões"
        ordering = ['subdominio__name']

And in my view I basically pass an argument that I use to verify the question (an id) and from it I get the question, after I get the question I pass it as argument and pull the alternatives. I would like to pass this information to the form, so I can process the form, check if a question is correct, etc.

Question view code:

def pergunta(request, slug, id):

    certificacao = get_object_or_404(Certificacao, slug=slug)
    situacao = Situacao.objects.get(certificado__id=id)
    resolucao = Resolucao.objects.get(situacao=situacao)
    questao = Questao.objects.get(resolucao=resolucao)
    alternativa = Alternativa.objects.filter(questao=questao)

    if request.method == 'POST':
        form = QuestaoForm(request.POST)

        if form.is_valid():
            return HttpResponse('Parabéns! Acertou!')

    else:
        form = QuestaoForm()

    return render(request, 'certificacoes/pergunta.html', {'form': form})

I would like to show the information basically like this, then when clicking on the Ubmit I would check the boolean if the question was correct and such, but I’m days stuck in this and I have no idea how to solve. Thank you!

inserir a descrição da imagem aqui

  • I answered an identical question to that, see here. If you want to keep this question, show the code of the view and template, to give subsidies to those who want to help.

  • I edited with the view, Sidon. Thank you and I will read on your post.

  • Read, but give Ctrl-c/Ctrl-v in the code (there are only 2 minimal files) and run in your environment, as I suggest, and you will understand, qq doubt ask la.

1 answer

2


I did something similar, I about wrote the init form method. At the time of instantiating the form I pass the parameters I want to:

form = QualquerForm(request.POST,var1='ola mundo')

Now about writing the form method:

class QualquerForm(forms.Form):

    def __init__(self,*args, **kwargs):
        self.var1 = kwargs.get('var1',None)
        super(QualquerForm, self).__init__(*args, **kwargs) 

So I can access in any method the variable passed like this:

self.var1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.