Skip to content
Advertisement

Associate a Django Bool FormField with a submit button in a ModelForm and CBV

The view has a Boolean Field which will define if a question is OK or needs correction. The template will load two buttons to act as submit to the form, “Question is OK” and “Question needs correction”. I need to pass the value of this button as the Boolean Field value. I found the answer when using Function-based views, but I’m using Class-based views, so I don’t know how to pass the request.POST values.

Here’s my views.py and forms.py:

views.py

class QuestionValidation(PermissionRequiredMixin, UpdateView):
permission_required = 'users.validator'
model = Question
form_class = ValidationForm
template_name = 'question_validation.html'

def get_context_data(self, *args, **kwargs):
    context = super().get_context_data(**kwargs)
    context['question'] = Question.objects.filter(
        question_order=self.kwargs['order']).get(id_by_order=self.kwargs['id_by_order'])
    context['order'] = self.kwargs['order']
    context['id_by_order'] = self.kwargs['id_by_order']
    return context

def get_object(self, *args, **kwargs):
    question_order = Q(question_order__id=self.kwargs['order'])
    question_id = Q(id_by_order__contains=self.kwargs['id_by_order'])
    q = Question.objects.get(question_order & question_id)
    return get_object_or_404(Question, pk=q.id)

def get_success_url(self, *args, **kwargs):
    view_name = "order-detail"
    return reverse(view_name, kwargs={'pk': self.kwargs['order']})

forms.py

class ValidationForm(forms.ModelForm):
    class Meta:
        model = Question
        fields = ['revision_report', 'revision_approval']
        widgets = {
            'revision_report': forms.HiddenInput(),
            'revision_approval': forms.HiddenInput(),
        }

and part of the template that this code will be loaded:

  <form action="" method="POST">{% csrf_token %}
    {{ form.as_p }}
    <button class="btn btn-success" name="question_approved">Questão aprovada</button>
    <button class="btn btn-danger" name="question_refused">Questão não foi aprovada</button>
  </form>
  <br><br>
  <script src="{% static 'js/hoverValidatorTextbox.js' %}"></script>
{% endblock %}

Advertisement

Answer

As Ene P told in the comments the following link solves it.

https://docs.djangoproject.com/en/3.2/topics/class-based-views/intro/#handling-forms-with-class-based-views

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement