0
I need to check if a "checkbox" button, called yes_no, was selected in my html page and modify the "name" field to mandatory when this checkbox is triggered. My code is this:
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 file Forms.py:
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 file views.py:
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>
It worked correctly, however the validation error 'The name field is required' did not appear when I applied my form.
– Matheus Sant'ana
Your template is not rendering field errors.
– ThiagoO
All right now!
– Matheus Sant'ana
Managed to render errors ??
– ThiagoO
I did, just by including the code {{ form.yes_no.errors }} in my template the error appeared! Thanks for the help!
– Matheus Sant'ana
I just did a test with another code, I’m getting an error like Keyerror at /profile/config. I did the exact same thing, you would know why?
– Matheus Sant'ana
You could post the whole mistake for me to look at ?
– ThiagoO
Keyerror at /profile/config 'b2c_active'
– Matheus Sant'ana