Issue
I am new to Django, I have to do a simple web page to register people. Some names is in Portuguese, but it does not matter. I do not know what I am doing wrong, maybe I am sending empty data to the view, but I am not sure. view.py:
def get_form(request):
logger = logging.getLogger('django')
logger.info("Request")
if request.method == 'POST':
logger.info("POST method")
form = cadastroForm(request.POST)
logger.info(form.errors)
if form.is_valid():
logger.info("Valid")
insert_data(form.cleaned_data['nome'], form.cleaned_data['mat'], form.cleaned_data['telefone'], form.cleaned_data['email'])
return HttpResponseRedirect(reverse('all-borrowed'))
else:
logger.info("Not Valid")
else:
form = cadastroForm()
html page:
{% block page_content %}
<h1 style="text-align: center; margin-top: 10%; margin-bottom: 5%; font-size: 64px;">Cadastro</h1>
<form action="../../views.py" style="display: inline-block; margin-left: 40%;" method = "POST">
{% csrf_token %}
<label for="nome">Nome:</label>
<input type="text" id="nome" name="nome" style="margin-left: 30px" maxlength="100" required><br><br>
<label for="telefone">Telefone:</label>
<input type="text" id="telefone" name="telefone" style="margin-left: 10px" required><br><br>
<label for="email">Email:</label>
<input type="text" id="email" name="email" style="margin-left: 36px" required>
<p style="margin-top: 15px;">Frequenta o IESB:
<input type="radio" id="iesb_sim" name="iesb" value="Yes" required><label for="iesb_sim" style="margin-left: 5px">Sim</label>
<input type="radio" id="iesb_nao" name="iesb" value="No" required checked="checked"><label for="iesb_nao" style="margin-left: 5px">Não</label>
</p>
<label for="mat">Matrícula:</label>
<input type="text" id="mat" name="mat">
<br><br>
<input type="file" style="margin-bottom: 18px" id="myFile" name="filename">
<input type="submit" value="Enviar" style="margin: auto; display: block;">
</form>
<script>
document.getElementById("iesb_sim").addEventListener("change", function(){
document.getElementById("mat").disabled = false;
})
document.getElementById("iesb_nao").addEventListener("change", function(){
document.getElementById("mat").disabled = true;
})
</script>
{% endblock page_content %}
forms.py:
class cadastroForm(forms.Form):
nome = forms.CharField(label="Nome completo", required=True, max_length=100)
telefone = forms.CharField(label="Telefone", required=True, max_length=100)
email = forms.EmailField(label="Email", required=True)
b_iesb = forms.RadioSelect(choices=["Yes", "No"])
mat = forms.IntegerField(label="Matrícula")
foto = forms.ImageField(label="Foto")
def clean(self):
cleaned_data = super().clean()
nome = cleaned_data.get("nome")
tele = cleaned_data.get("telefone")
email = cleaned_data.get("email")
b_iesb = cleaned_data.get("iesb")
mat = cleaned_data.get("mat")
#foto = cleaned_data.get("filename")
if not nome.istitle():
nome = nome.Title()
if re.search("[a-zA-Z]", tele) != None:
raise ValidationError(_(
"O número de telefone não pode possuir letras"
))
validate_email(email)
if b_iesb == "Yes":
if mat == None:
raise ValidationError(_(
"Se frequenta o IESB, deve possuir uma matrícula"
))
- Fill free to recommend updates, what I can do better with Django
I need the name, the phone number, email, if it is a Yes at the radio button I need the registration, and a photo file. The error I am getting the telefone, and foto is required, even I sent those
Solution
Answer to the question
Make sure to return the cleaned_data
* in the end. When the clean()
method does not return data the error "XYZ is required" is thrown because it "did not survive" your clean()
method (simply because it was not returned). Stick to the following template:
from django import forms
class MyForm(forms.Form):
# Your form fields here
def clean(self):
cleaned_data = super().clean()
# Perform your custom validation and cleaning here
# Always return cleaned_data
return cleaned_data
Additional recommendations
The end of your view function probably returns a call to the render
function which gets passed: request
, template
and context
. That context can hold the form. That form can be accessed from within the template and saves you a lot of typing work.
# your view function
def get_form(request):
[... your logic ...]
return render(request, 'your-template.html', context={form: form})
your template:
{% block page_content %}
<h1 style="text-align: center; margin-top: 10%; margin-bottom: 5%; font-size: 64px;">Cadastro</h1>
<form action="../../views.py" style="display: inline-block; margin-left: 40%;" method = "POST">
{% csrf_token %}
{{ form }}
<input type="submit" value="Enviar" style="margin: auto; display: block;">
</form>
<script>
document.getElementById("iesb_sim").addEventListener("change", function(){
document.getElementById("mat").disabled = false;
})
(more info)
Answered By - Tarquinius
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.