I need to check if a "checkbox" button, called yes_no, was selected on my html page and change the "name" field to mandatory when this checkbox is triggered. My code is as follows:
In the models.py file:
from django.db import models
# Create your models here.
class RandomModel(models.Model):
name = models.CharField(max_length=200)
shirt_size = models.IntegerField()
yes_no = models.BooleanField()
In the forms.py file:
from django import forms
from .models import RandomModel
class RandomForm(forms.ModelForm):
name = forms.CharField(required=False)
class Meta:
model = RandomModel
fields = ['name', 'shirt_size', 'yes_no']
In the views.py file:
from django.shortcuts import render
from .forms import *
from django.shortcuts import redirect
# Create your views here.
def random_view(request):
if request.method == 'POST':
form = RandomForm(request.POST)
if form.is_valid():
form.save()
return redirect('learn:random')
else:
form = RandomForm()
return render(request, 'learn/index.html', {'form': form})
In the index.html file:
{% load staticfiles %}
<form action="{% url 'learn:random' %}" method="post">
{% csrf_token %}
{{ form.name }}
{{ form.shirt_size }}
{{ form.yes_no }}
<input type="submit" value="Enviar">
</form>