Im not using forms.py to generate my contact area of website, but i want to add captcha in my form.
I try to create only the captcha form in forms.py by doing this:
from django import forms
from captcha.fields import CaptchaField
class CaptchaTestForm(forms.Form):
captcha = CaptchaField()
But this do not seems to work.
Any solutiosn?
I'm just using the tag {{ form.as_p}} inside the form
EDIT
This is my view:
def home(request):
if request.method == 'POST':
form = CaptchaTestForm(request.POST)
nome = request.POST.get('nome', None)
assunto = request.POST.get('assunto', None)
email = request.POST.get('email', None)
mensagem = request.POST.get('mensagem', None)
if form.is_valid():
if nome and assunto and email and mensagem:
try:
conteudo = 'Nome: %s\nAssunto: %s\nEmail: %s\nMensagem: %s' % (nome, assunto, email, mensagem.strip())
send_mail('Contato via site Dona Rita', conteudo, EMAIL_HOST_USER,
['contato#witalobenicio.com'], fail_silently=True)
messages.success(request, 'Recebemos o seu contato. Em breve entraremos retornaremos.')
except SMTPException:
messages.error(request, 'Ocorreu um erro ao enviar o e-mail mas já estamos solucionando,\
tente novamente mais tarde.')
else:
messages.error(request, 'Preencha os campos corretamentes.')
slider = Slider.objects.all()
promocoes = Promocao.objects.all()
categorias = Categoria.objects.all()
produtos = Produto.objects.all()
cardapio = {}
for categoria in categorias:
myproducts = []
cardapio[categoria.name] = ''
for produto in produtos:
if produto.category == categoria:
myproducts.append(produto)
cardapio[categoria.name] = myproducts
od = collections.OrderedDict(sorted(cardapio.items()))
return render_to_response('signups.html', {'produtos':od,'promocoes':promocoes, 'slider':slider}, context_instance=RequestContext(request))
And this is my template
<form role="form" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="name">Nome</label>
<input type="text" class="form-control" id="name" placeholder="Seu nome" name="nome">
</div>
<div class="form-group">
<label for="subject">Assunto</label>
<input type="text" class="form-control" id="subject" placeholder="Assunto da Mensagem" name="assunto">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" placeholder="Digite seu email" name="email">
</div>
<div class="form-group">
<label for="message">Mensagem</label>
<textarea class="form-control" rows="3" placeholder="Digite sua Mensagem" id="message" name="mensagem"></textarea>
</div>
{{ form }}
<button type="submit" class="btn btn-default">Enviar</button>
</form>
You are not sending CaptchaTestForm to user when user makes a get request.
To do that, import CaptchaTestForm in your view.
from .forms import CaptchaTestForm
Replace last line of your view with this to send that form.
form = CaptchaTestForm()
return render_to_response('signups.html', {'produtos':od,'promocoes':promocoes,
'slider':slider, 'form': CaptchaTestForm},
context_instance=RequestContext(request))
Related
This question already has answers here:
The view didn't return an HttpResponse object. It returned None instead
(7 answers)
Closed last month.
ValueError at /update_department/14
The view management.views.update_department didn't return an HttpResponse object. It returned None instead.Also when added with return statement data is not updating.
Request information
USER
admin
GET
No GET data
POST
Variable Value
csrfmiddlewaretoken
'XLqZBPhMKImvlfgWsNLeN1Ei8nz5u1HJ15IvAQV4JNwVMeG31rhDOD1q9PJuwXmz'
department_code
'15'
department_name_e
'Finance'
department_name_l
'Finance'
parent_code
''
submit
''
These are the details.I don't know why is there error here while all the posted data is right.also the form is not updating.
Models:
class Departments(models.Model):
department_code = models.CharField(db_column='Department_Code', primary_key= True, max_length=20, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
department_name_e = models.CharField(db_column='Department_Name_E', max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
department_name_l = models.CharField(db_column='Department_Name_L', max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
parent_code = models.CharField(db_column='Parent_Code', max_length=20, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
is_active = models.BooleanField(db_column='Is_Active') # Field name made lowercase.
created_by = models.IntegerField(db_column='Created_By') # Field name made lowercase.
created_date = models.DateTimeField(db_column='Created_date') # Field name made lowercase.
modified_by = models.IntegerField(db_column='Modified_By') # Field name made lowercase.
modified_date = models.DateTimeField(db_column='Modified_date') # Field name made lowercase.
class Meta:
db_table = 'Departments'
unique_together = (('department_code'),)
def __str__(self):
return str("self.department_name_e") or ''
View:
#login_required
def update_department(request, department_code):
dep_up = Departments.objects.get(department_code=department_code)
if request.method == "POST":
form = DepartmentsForm(request.POST, instance = dep_up)
if form.is_valid():
department_code = form.cleaned_data['department_code']
department_name_e = form.cleaned_data['department_name_e']
department_name_l = form.cleaned_data['department_name_l']
parent_code = form.cleaned_data['parent_code']
obj = form.save(commit = False)
obj.is_active = True
obj.created_by = request.user.id
obj.created_date = datetime.today()
obj.modified_by = request.user.id
obj.modified_date = datetime.today()
obj.save()
return HttpResponseRedirect('department_list')
forms:
class DepartmentsForm(forms.ModelForm):
class Meta:
model = Departments
fields = ['department_code','department_name_e','department_name_l','parent_code']
HTML:
{% extends 'base.html' %}
{% block title %}Update Company{% endblock title %}
{% block body %}
<div style="margin-left:22%" class=" top-marg">
<h2 ><strong>Company:</strong></h2><br><br>
<form class="" action="{%url 'update_company' comp_up.company_code %}" method="post">
{% csrf_token %}
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="text" value="{{comp_up.company_code}}" class="form-control" id="company_code" name="company_code" placeholder="Company Code" required>
<label style="margin-left:15px" for="company_code">Company Code</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="text" value="{{comp_up.company_name_e}}" class="form-control" id = "company_name_e" name="company_name_e" placeholder="Enter Company" required>
<label style="margin-left:15px" for="company_name_e">Company Name English</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="text" value="{{comp_up.company_name_l}}" class="form-control" id = "company_name_l" name="company_name_l" placeholder="Enter Company" required>
<label style="margin-left:15px" for="company_name_e">Company Name Local</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="tel" value="{{comp_up.tel}}" class="form-control" id = "tel" name="tel" placeholder="Telephone Number" required>
<label style="margin-left:15px" for="tel">Telephone Number</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="tel" value="{{comp_up.fax}}" class="form-control" id = "fax" name="fax" placeholder="Enter Fax"required>
<label style="margin-left:15px" for="fax"> Fax Number</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<textarea name="address" class="form-control" rows="4" cols="100" placeholder="Address" required>{{comp_up.address}}</textarea>
<label style="margin-left:15px" for="address">Address</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<select class="form-control" name="country_id" required>
<option value="{{comp_up.country_id.id}}" >{{comp_up.country_id.country_name_e}}</option>
{% for con in country %}
<option value="{{con.id}}" >{{con.country_name_e}}</option>
{% endfor %}
</select>
</div>
<br>
<label style = "margin-left:21%; " for="logo">Logo</label>
<div class="form-floating" >
<input value="{{comp_up.}}" style = "margin-left:21%;" accept="image/*" type="file" name="logo" onchange="loadFile(event)" required> <br>
<img style = "margin-left:21%;" id="output" >
<script>
var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
output.onload = function() {
URL.revokeObjectURL(output.src) // free memory
}
};
</script>
</div>
<br><br>
<center>
<button type="submit" class="btn btn-success" name="submit">Update</button>
<button type="button" class="btn btn-primary" onclick="window.location.href = '{%url 'company_list'%}'" name="cancel">Cancel</button>
</center>
</form>
</div>
{% endblock body %}
You have provided HttpReponse only for POST and valid form. You should give the standard response (with empty form) for fresh entries or posting with errors. Like this:
#login_required
def update_department(request, department_code):
dep_up = Departments.objects.get(department_code=department_code)
if request.method == "POST":
form = DepartmentsForm(request.POST, instance = dep_up)
if form.is_valid():
...
return HttpResponseRedirect('department_list')
form = DepartmentsForm()
return render(request, 'template.html', context={'form': form})
I want to Update/Edit my details on my form. I want to pull the existing details from the database and have them populate on the form, without having the user start from the beginning.
Views.py
def Client_Update(request, Client_id):
ClientUpdate = TestModel.objects.get(pk=Client_id)
ClientUpdates = TestForm(request.POST or None, instance=ClientUpdate)
if request.method == 'POST':
if ClientUpdates.is_valid():
ClientUpdates.save()
return redirect('/Client_Details')
return render(request, 'GymApp/ClientUpdate.html',
{'ClientUpdate':ClientUpdate,
'ClientUpdates':ClientUpdates})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.Home, name='Home'),
path('ClientList/', views.Client_list, name='Client_list'),
path('ClientDetails/<int:Client_id>', views.Client_Details, name='Client_Details'),
path('ClientUpdate/<int:Client_id>', views.Client_Update, name='Client_Update'),
path('ClientDelete/<int:Client_id>', views.Client_Delete, name='Client_Delete'),
path('DownloadingCSV/', views.DownloadingCSV, name='DownloadingCSV'),
path('Search/', views.Search, name='Search'),
]
HTML Page
{% extends 'GymApp/Layout.html' %}
{% block content %}
<h1>Updating status</h1>
<form action="" method="POST">
{% csrf_token %}
<div class="mb-3">
<input type="text" class="form-control"
name="Name" placeholder="Client's Name"><br>
<input type="text" class="form-control"
name="Surname"placeholder="Client's Surname"><br>
<select name="Gender" class="form-control">
<option selected disabled>
Open this select menu
</option>
<option value="Male">Male</option><br>
<option value="Female">Female</option>
</select>
</div>
<div class="mb-3">
<input type="text" class="form-control" name="Weight" id="Weight" placeholder="Client's Weight"><br><br>
<input type="text" class="form-control" name="Height" id="Height" placeholder="Client's Height"><br><br>
<button type="button" onclick="calculation()">Calculation update</button>
<br>
</div>
<br>
<div class="mb-3">
<input type="text" class="form-control" name="Outcome" id="Outcome" placeholder="BMI Outcome"><br>
<select name="Activity_log" class="form-control"><br>
<option selected disabled>Open this select menu</option>
<option value="Not Active">Not Active</option><br>
<option value="Active">Active</option>
</select>
<br>
<button type="submit">Finalising update!</button>
</div>
</form>
<script>
function calculation(){
W = document.getElementById('Weight').value;
H = document.getElementById('Height').value;
O = W * H;
document.getElementById('Outcome').value = O;
}
</script>
{% endblock %}
And the outcome when i press the Update button is the following:
As you can the form is empty
How to i pull the existing details on my form? Please help.
from django.db import models
# Create your models here.
class TestModel(models.Model):
Name = models.CharField(max_length=30, blank=True)
Surname = models.CharField(max_length=30, blank=True)
Weight = models.CharField(max_length=30, blank=True)
Height = models.CharField(max_length=30,blank=True)
Gender = models.CharField(max_length=6, blank=True, null=True)
Outcome = models.CharField(max_length=30,blank=True)
Activity = models.CharField(max_length=30, blank=True)
def __str__(self):
return self.Name
And this is my updated HTML
<form action="" method="POST">
{% csrf_token %}
<div class="mb-3">
<input type="text" class="form-control" name="Name" value={{Name}}><br>
<input type="text" class="form-control" name="Surname" value={{Surname}}><br>
<select name="Gender" class="form-control">
<option selected disabled>
Open this select menu
</option>
<option value="Male" value={{Gender}}>Male</option><br>
<option value="Female" value={{Gender}}>Female</option>
</select>
</div>
<div class="mb-3">
<input type="text" class="form-control" id="Weight" value={{Weight}} ><br><br>
<input type="text" class="form-control" id="Height" value={{Height}} ><br><br>
<button type="button" onclick="calculation()">Calculation update</button>
<br>
</div>
<br>
<div class="mb-3">
<input type="text" class="form-control" name="Outcome" id="Outcome" placeholder="BMI Outcome"><br>
<select name="Activity_log" class="form-control"><br>
<option selected disabled>Open this select menu</option>
<option value="Not Active">Not Active</option><br>
<option value="Active">Active</option>
</select>
<br>
<button type="submit">Finalising update!</button>
</div>
</form>
All my views.py
from django.shortcuts import render, redirect
from . models import TestModel
from . forms import TestForm
from django.http import HttpResponse
import csv
# Create your views here.
def Search(request):
if request.method == "POST":
Searching = request.POST['Searching']
Results_query = TestModel.objects.filter(Name__contains=Searching)
{'Searching':Searching,
'Results_query':Results_query}
return render(request, 'GymApp/Searching.html',
{'Searching':Searching,
'Results_query':Results_query})
def DownloadingCSV(request):
response = HttpResponse(content_type='text/csv')
response['content-disposition'] = 'attachment; filename=Client_list.csv'
writer = csv.writer(response)
Downloading_all = TestModel.objects.all()
writer.writerow(['Name','Surname',
'Weight','Height',
'Outcome','Gender',
'Activity'])
for download in Downloading_all:
writer.writerow([download.Name,
download.Surname,
download.Weight,
download.Height,
download.Outcome,
download.Gender,
download.Activity])
return response
def Client_Delete(request, Client_id):
ClientUpdate = TestModel.objects.get(pk=Client_id)
ClientUpdate.delete()
return redirect('Home')
def Client_Update(request, Client_id):
ClientUpdate = TestModel.objects.get(pk=Client_id)
ClientUpdates = TestForm(request.POST or None, instance=ClientUpdate)
if request.method == 'POST':
if ClientUpdates.is_valid():
ClientUpdates.save()
return redirect('/Client_Details')
return render(request, 'GymApp/ClientUpdate.html',
{'ClientUpdate':ClientUpdate,
'ClientUpdates':ClientUpdates})
def Client_list(request):
Clients = TestModel.objects.all()
return render(request, 'GymApp/ClientList.html',
{'Clients':Clients})
def Client_Details(request, Client_id):
ClientDetails = TestModel.objects.get(pk=Client_id)
return render(request, 'GymApp/ClientDetails.html',
{'ClientDetails':ClientDetails})
def Home(request):
Forms = TestForm
if request.method == 'POST':
Forms = TestForm(request.POST or None)
if Forms.is_valid():
Forms.save()
return redirect('Client_list')
return render(request, 'GymApp/Home.html',{})
### You have not given value
<input type="text" class="form-control"
name="Name" value={{ClientUpdates.Name}} placeholder="Client's Name"><br>
###{{Name}} --> your model field name
I have two forms:
auth.html
<form class="form-signin pt-5" action="/auth/" method="post" >
{% if error_msg: %}
{{ error_msg }}
{% endif %}
<div class="mt-5 form-label-group">
<p class="text-muted">email</p>
<input type="email" id="inputEmail" class="form-control" name = "email" required autofocus>
</div>
<div class="form-label-group">
<p class="text-muted"> password</p>
<input type="password" id="inputPassword" name="password" class="form-control" required>
<label for="inputPassword"></label>
</div>
<div class="checkbox mb-3"></div>
<button class="btn btn-lg btn-danger btn-block" type="submit">Enter</button>
</form>
success form.html
Success
code in flask is:
app = Flask(__name__)
app.secret_key = "randomstring"
app.config["SECRET_KEY"] = "secret_key"
app.config["EMAIL"] = "test#test.ru"
app.config["PASSWORD"] = "test"
#app.route("/auth/", methods=["GET", "POST"])
def auth_open():
error_msg = "" # Пока ошибок нет
if request.method == "POST":
email = request.form.get("username")
password = request.form.get("password")
if ((email and password) and email == app.config["EMAIL"] and password == app.config["PASSWORD"]):
session["is_auth"] = True
return render_template("/")
else:
error_msg = "Error login or password"
return render_template("auth.html", error_msg=error_msg)
When I input password and login it shows me error message instead of success form.How should I solve this problem?
email = request.form.get("email")
So I have a form which takes some input and a file field. I'm using a validator on the file filed to check for the size of the file. It is working well because I get the error on the page saying that the file is too large, but the entry still gets into the DB.
I don't know why this happens. I supposed that raising an exception would do the trick in my case, but it does not.
models.py
from django.db import models
from django.contrib.auth.models import User
from .validators import validate_file_size
# Create your models here.
class CV(models.Model):
solicitant = models.ForeignKey(User, on_delete=models.CASCADE)
dataUploadCV = models.DateField(auto_now_add=True)
nume = models.CharField(max_length=12)
prenume = models.CharField(max_length=12)
telefon = models.CharField(max_length=12)
emailContact = models.EmailField(max_length=40)
CV = models.FileField(upload_to='documents/%d/%m/%Y', validators=[validate_file_size])
rezolvata = models.BooleanField(default=False)
def __str__(self):
return self.nume + " " + self.prenume + ": " + str(self.CV)
validators.py
from django.core.exceptions import ValidationError
def validate_file_size(value):
filesize=value.size
if filesize > 1:
raise ValidationError("Fisierul poate avea maxim 5MB.")
else:
return value
views.py
from django.shortcuts import render, get_object_or_404
from .models import Oferta, CV
from django.contrib import messages
from django.core.paginator import Paginator
# Create your views here
def incarcarecv(req):
context = {
'title': "Incarcare CV | Best DAVNIC73"
}
if req.method == 'POST':
try:
nume = req.POST['nume']
prenume = req.POST['prenume']
telefon = req.POST['telefon']
email = req.POST['email']
cv = req.FILES['CV']
try:
if(req.user.is_authenticated):
cv_upload = CV(
solicitant=req.user,
nume=nume,
prenume=prenume,
telefon=telefon,
emailContact=email
)
cv_upload.CV.save(cv.name, cv)
cv_upload.full_clean()
cv_upload.save()
req.user.profile.cvuri.append(cv_upload.id)
req.user.profile.save()
messages.success(req, 'CV depus cu succes!')
else:
messages.error(req, 'Trebuie sa fii logat pentru a depune CV-ul!')
except (ValueError):
messages.error(req, 'Formularul nu a fost incarcat!')
messages.info(req, 'Verifica daca esti logat!')
except:
messages.error(req, 'Nu ai completat corect campurile sau unul din ele este liber!')
messages.info(req, 'Ai grija ca toate campurile sa fie completate si ca fisierul sa nu depaseasca 5MB!')
return render(req, "../templates/pagini/incarcare-cv.html", context)
html file
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="container container-centru">
<h1 class="heading-contact">Incarca CV</h1>
{% include 'partials/_alerts.html' %}
<form action="{% url 'incarcarecv' %}" method="POST" class="form-contact" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label for="inputnume" class="email-contact">Nume</label>
<input type="text" name="nume" class="form-control" id="inputnume" aria-describedby="numeHelp" placeholder="Introdu nume">
</div>
<div class="form-group">
<label for="inputprenume" class="email-contact">Prenume</label>
<input type="text" name="prenume" class="form-control" id="inputprenume" aria-describedby="prenumeHelp" placeholder="Introdu prenume">
</div>
<div class="form-group">
<label for="inputtelefon" class="email-contact">Telefon</label>
<input type="text" name="telefon" class="form-control" id="inputtelefon" aria-describedby="telefonHelp" placeholder="Introdu telefon">
</div>
<div class="form-group">
<label for="inputemail" class="email-contact">Email</label>
<input type="email" name="email" class="form-control" id="inputemail" aria-describedby="emailHelp" placeholder="Introdu email">
</div>
<div class="form-group">
<label for="inputcv" class="email-contact">CV</label>
<input type="file" name="CV" accept=".docx,.doc,.pdf,application/msword" class="form-control" id="inputemail" aria-describedby="CVHelp">
</div>
<div class="form-group form-group-custom">
<input type="submit" value="Trimite" class="btn btn-secondary btn-block btn-login-custom">
<input type="submit" value="Resetează câmpurile" class="btn btn-secondary btn-block btn-reset-custom">
</div>
</form>
</div>
<script src="{% static 'javascript/clearMessage.js' %}"></script>
{% endblock %}
So how can I make the post not enter the DB if the exception is thrown? Right now I get the error, but it is still entering the DB. (I can see it in the administration zone of django)
////edit: I deleted everything that was not about my problem from the code.
////edit2: added the HTML file
In Django, the typical workflow is to first run validators to verify that the data you are trying to commit into the database is "clean" and only then should one call save(). But due to some quirks calling save does not automatically clean the data.
so the workflow should be something along the lines of:
...
cv_upload = CV(solicitant=req.user, nume=nume, prenume=prenume,
telefon=telefon, emailContact=email)
# call clean before saving as we only want CLEAN data in the DB
cv_upload.full_clean()
# now that it is relatively clean with Django's validators and our custom validators
# go ahead and save it
cv_upload.save()
...
I've create a Model, Form, View and register.html but my form doesn't save on database and doesn't create a new user. What's wrong?
Follow the codes...
models.py
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
class Cliente(models.Model):
SEXO_CHOICES = (
(u'Masculino', u'Masculino'),
(u'Feminino', u'Feminino'),
)
nome = models.CharField(max_length=50, null=False, default='*')
telefone = models.CharField(max_length=20, null=True)
cpf = models.CharField(max_length=255, null=False)
data_de_nascimento = models.DateField(null=False)
sexo = models.CharField(max_length=9, null=False, choices=SEXO_CHOICES)
usuario = models.OneToOneField(User, related_name="cliente")
#property
def email(self):
return self.usuario.email
def __unicode__(self):
return self.nome
forms.py
from django import forms
from django.contrib.auth.models import User
from datetimewidget.widgets import DateTimeWidget, DateWidget, TimeWidget
from clientes.models import Cliente
class RegistraClienteForm(forms.Form):
SEXO_CHOICES = (
(u'Masculino', u'Masculino'),
(u'Feminino', u'Feminino'),
)
nome = forms.CharField(required=True)
telefone = forms.CharField(required=True)
cpf = forms.CharField(required=True)
data_de_nascimento = forms.DateField(
widget=DateWidget(usel10n=True, bootstrap_version=3)
)
sexo = forms.ChoiceField(required=True, choices=SEXO_CHOICES)
username = forms.CharField(required=True)
email = forms.EmailField(required=True)
senha = forms.CharField(required=True)
def is_valid(self):
valid = True
if not super(RegistraClienteForm, self).is_valid():
self.adiciona_erro('Por favor, verifique os dados informados')
valid = False
return valid
username_form_data = self.data['username']
user_exists = User.objects.filter(username=username_form_data).exists()
if user_exists:
self.adiciona_erro('User already exists!')
valid = False
return valid
def adiciona_erro(self, message):
errors = self._errors.setdefault(
forms.forms.NON_FIELD_ERRORS,
forms.utils.ErrorList()
)
errors.append(message)
And the register.html
{% extends "new_client_base.html" %}
{% block body %}
<form class="form-signin" action="{% url 'registrar' %}" method="post">
{% csrf_token %}
<h2 class="form-signin-heading">Crie seu usuário</h2>
<label for="id_nome"> Nome: </label> <input name="nome" type="text" id="id_nome" class="form-control" placeholder="Nome *" required autofocus/>
<label for="id_telefone">Telefone: </label> <input type="text" name="telefone" id="id_telefone" class="form-control" placeholder="Telefone *" required/>
<label for="id_cpf"> CPF: </label> <input type="text" name="cpf" id="id_cpf" class="form-control" placeholder="CPF *" required/>
<label for="id_data"> Data de Nascimento:</label> <input type="date" name="data_de_nascimento" id="id_data" class="form-control" required />
<label for="id_sexo" class="required">
Sexo:
</label> <select id="id_sexo" name="sexo">
<option selected="selected" value=""> ------- </option>
<option value="Masculino"> Masculino </option>
<option value="Feminino"> Feminino </option>
</select>
<label for="id_username"> Nome de usuário: </label> <input type="text" name="username" class="form-control" id="id_username" required/>
<label for="id_email"> Email: </label> <input type="text" name="email" id="id_email" class="form-control" required />
<label for="id_pass"> Senha: </label> <input type="password" name="senha" id="id_pass" class="form-control" required>
<button
type="submit"
class="btn btn-lg btn-primary btn-block"
value="login"
>
Registrar
</button>
{% if form.errors %}
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true" name="button">×</button>
{{form.non_field_errors}}
</div>
{% endif %}
</form>
{% endblock %}
I want to know how to save this data, why save() method does not work and how can I format date in DD-MM-YYYY and show a minicalendar.
Thanks.