The imageField doesnt upload images django - python

I am trying to upload pictures from an imageField, but it doesn't upload anything when I try.
models.py
def upload_location(instance, filename):
return "uploads/%s/img/%s/" % (instance.id, filename)
class CustomUser(AbstractBaseUser, PermissionsMixin):
...
width_field = models.IntegerField(default=0)
height_field = models.IntegerField(default=0)
photo = models.ImageField(
upload_to=upload_location,
null=True, blank=True,
width_field="width_field",
height_field="height_field"
)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
objects = UserManager()
forms.py
class UserConfigurationForm(UserChangeForm):
class Meta:
model=CustomUser
fields = ('first_name', 'last_name', 'email', 'phone_number',
'direction', 'password', 'photo',)
views.py
def configuration(request):
categoria = Clasificacion.objects.filter(existencia=True)
templates = Templates.objects.get(isSelected=True)
if request.method == 'GET':
form = UserConfigurationForm(instance=request.user)
else:
form = UserConfigurationForm(request.POST or None, request.FILES or None, instance=request.user)
if form.is_valid():
form.save()
return redirect('myuser:myuser')
return render(request, 'myuser/configuration.html', {'form': form, 'categoria':categoria,'templates':templates})
template
<form method="post" action='' enctype="multipart/form-data">
{%csrf_token%}
<div class="col-sm-8 ">
<strong>{{form.photo}}</strong></div>
<!--FIRST NAME-->
<label for="first_name">Nombre</label>
<div class="form-group">
<input class= "form-control" type="text" name="first_name" maxlength="20" value="{{user.first_name}}" required>
</div>
<label for="last_name">Apellidos</label>
<div class="form-group">
<input class="form-control" type="text" name="last_name" value="{{user.last_name}}">
</div>
<!--Username and email is same in this case-->
<label for="last_name">Correo electrónico</label>
<div class="form-group">
<input class= "form-control" type="email" name="email" value="{{user.email}}" required>
</div>
<!--Phone number-->
<label for="phone_number">Teléfono</label>
<div class="form-group">
<input class= "form-control" type="tel" pattern="[0-9]{4}-[0-9]{3}-[0-9]{4}" name="phone_number" placeholder="Formato ejem: 0414-685-4716" value="{{user.phone_number}}"required>
</div>
<!--Direction-->
<label for="direction">Dirección</label>
<div class="form-group">
<textarea id="direction" class= "form-control" rows="6" name="direction"
value="{{user.direction}}" required>{{user.direction}}</textarea>
</div>
<!--SUBMIT-->
<div class="form-group">
<div class="col-xs-12">
<br>
<button type="submit" class="btn btn-lg btn-success">Guardar cambios</button>
</div>
</form>
I did it before but I don't know what is causing this. The other fields are working fine, I just have the problem with the photo. I put the enctype, and the request.FILES but it doesn't work.
Hope you can help me! Thank you!

Related

I'm a newbie to python/Django and getting a value error and no http response error. Also when added with return statement, form is not updating [duplicate]

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})

How to set the current date to an input type = date form in Django

I have been trying to make the date field in a form to display the current date when it renders. But I have failed to find a proper solution to this problem.
Please find below the code.
HTML File
<form class="form-horizontal" role="form" method = 'POST'>
{% csrf_token%}
<h2>New Manufacturer Details</h2>
<div class="form-group row">
<label for="createddate" class="col-sm-3 control-label">Created Date</label>
<div class="col-sm-9">
<input type="date" id="createddate" name = "createddate" class="form-control" autofocus required="true" value = '{{ createddate }}'>
</div>
</div>
<div class="form-group row">
<label for="manufname" class="col-sm-3 control-label">Name</label>
<div class="col-sm-9">
<input type="text" id="manufname" name = "manufname" placeholder="Manufacturer Name" class="form-control" autofocus required="true" value = '{{ manufname }}'>
</div>
</div>
<div class="form-group row">
<label for="manufaddress" class="col-sm-3 control-label">Address</label>
<div class="col-sm-9">
<textarea class="form-control" id="manufaddress" name = "manufaddress" placeholder="Manufacturer Address" rows="3" required="true" value = '{{ manufaddress }}'></textarea>
</div>
</div>
<div class="form-group row">
<label for="manufcontact" class="col-sm-3 control-label">Contact Name</label>
<div class="col-sm-9">
<input type="text" id="manufcontact" name = "manufcontact" placeholder="Manufacturer POC" class="form-control" autofocus required="true" value = '{{ manufcontact }}'>
</div>
</div>
<div class="form-group row">
<label for="manufcontactnum" class="col-sm-3 control-label">Contact Number</label>
<div class="col-sm-9">
<input type="text" id="manufcontactnum" name = "manufcontactnum" placeholder="Manufacturer Contact Number" class="form-control" autofocus required="true" value = '{{ manufcontactnum }}'>
</div>
</div>
<div class="form-group row">
<label for="manufemailid" class="col-sm-3 control-label">Email Id</label>
<div class="col-sm-9">
<input type="email" id="manufemailid" name = "manufemailid" placeholder="Manufacturer Email Id" class="form-control" autofocus required="true" value = '{{ manufemailid }}'>
</div>
</div>
<div class="form-group row">
<label for="manufgst" class="col-sm-3 control-label">GST No</label>
<div class="col-sm-9">
<input type="text" id="manufgst" name = "manufgst" placeholder="Manufacturer GST Number" class="form-control" autofocus required="true" value = '{{ manufgst }}'>
</div>
</div>
<div class="form-group row">
<label for="manuflicenseno" class="col-sm-3 control-label">License No</label>
<div class="col-sm-9">
<input type="text" id="manuflicenseno" name = "manuflicenseno" placeholder="Manufacturer License Number" class="form-control" autofocus required="true" value = '{{ manuflicenseno }}'>
</div>
</div>
<div class="form-group row">
<label for="manufbank" class="col-sm-3 control-label">Bank Details</label>
<div class="col-sm-9">
<textarea class="form-control" id="manufbank" name = "manufbank" placeholder="Manufacturer Bank Details" rows="3" required="true" value = '{{ manufbank }}'></textarea>
</div>
</div>
<div class="col text-center">
<button type="submit" class="btn btn-primary" id="form-submit">Save</button>
</div>
</form> <!-- /form -->
<script>
$("#form-horizontal").validate();
</script>
Views.Py
def createmanufacturer(request):
if request.method == 'POST':
form = CreateManufacturerForm(request.POST or None)
if form.is_valid():
form.save()
else:
createddate = request.POST['createddate']
manufname = request.POST['manufname']
manufaddress = request.POST['manufaddress']
manufcontact = request.POST['manufcontact']
manufcontactnum = request.POST['manufcontactnum']
manufemailid = request.POST['manufemailid']
manufgst = request.POST['manufgst']
manuflicenseno = request.POST['manuflicenseno']
manufbank = request.POST['manufbank']
messages.success(request, ('There was an error in your form! Please try again...'))
return render(request, 'screens/createmanufacturer.html', {
'createddate' : createddate,
'manufname' : manufname,
'manufaddress' : manufaddress,
'manufcontact' : manufcontact,
'manufcontactnum' : manufcontactnum,
'manufemailid' : manufemailid,
'manufgst' : manufgst,
'manuflicenseno' : manuflicenseno,
'manufbank' : manufbank,
})
messages.success(request, ('Manufacturer Details have been submitted successfully'))
return redirect("screens:testpage")
else:
form = CreateManufacturerForm()
return render(
request = request,
template_name = 'screens/createmanufacturer.html',
context = {'form' : form}
)
forms.py
class CreateManufacturerForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CreateManufacturerForm, self).__init__(*args, **kwargs)
self.fields['createddate'].initial = date.today
class Meta:
model = Manufacturer
#createddate = forms.DateField(initial=date.today)
fields = ['createddate',
'manufname',
'manufaddress',
'manufcontact',
'manufcontactnum',
'manufemailid',
'manufgst',
'manuflicenseno',
'manufbank']
models.py
class Manufacturer(models.Model):
createddate = models.DateField()
manufname = models.CharField(max_length = 255)
manufaddress = models.TextField()
manufcontact = models.CharField(max_length = 255)
manufcontactnum = models.CharField(max_length = 25)
manufemailid = models.EmailField(max_length = 200)
manufgst = models.CharField(max_length = 255)
manuflicenseno = models.CharField(max_length = 255)
manufbank = models.TextField()
manufcode = models.CharField(max_length = 255, primary_key=True, editable=False)
def __str__(self):
return self.manufname
Right now, nothing happens when the form renders. What I want is the date in the Created Date should be set to today's date. However the user could leave it as is or could select a date of his/her choice. But the requirement is that date field should be pre-populated with the current date.
Please find below the screenshot of the web form.
Web Form
To save the current use auto_now=True
class DateField(auto_now=False, auto_now_add=False, **options)¶
A date, represented in Python by a datetime.date instance. Has a few extra, optional arguments:
DateField.auto_now¶
Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override
To display current date in the form use :
form = CreateManufacturerForm(initial={'createddate': datetime.now()})
So, after a lot of frustrating hours, I was able to finally solve the problem, with help from my friend Houda. This is what I did.
views.py
In the GET portion of the code, I wrote the following.
initial_data = {
'createddate' : date.today().strftime("%Y-%m-%d"),
}
form = CreateManufacturerForm(initial = initial_data)
template.html file
I changed the following
<input type="date" id="createddate" name = "createddate" class="form-control" autofocus required="true" value = '{{ form.createddate.value }}'>
I am not sure if this is the best solution. But at least I got it to work. I believe the issue had something to do with the date format that HTML has for the
input type = 'date'
it only allows 'YYYY-mm-dd'
Thanks everyone.

I can't submit the form even if it is valid

I have used CreateView for a form, but the form is not being submitted even when it is valid. It just redirects to the same page again.I am using the form_id for from fields, and it even submitted once or twice but now it is just not working.
models.py
class Centre(models.Model):
name= models.CharField(max_length=50, blank=False, unique=True)
address = models.CharField(max_length =250)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format: '+999999999'. Up to 10 digits allowed.")
contact = models.CharField(max_length=100, blank=False)
phone = models.CharField(validators=[phone_regex], max_length=10, blank=True)
views.py
class centre(CreateView):
fields = ('name','address','contact','phone',)
model = Centre
success_url = reverse_lazy("NewApp:logindex")
def form_valid(self, form):
form.save()
return super(centre, self).form_valid(form)
template :
<form method="POST">
{% csrf_token %}
<div class="col col-md-12">
<div class="fieldWrapper" >
{{ form.name.errors }}
<div class="form-group col col-md-3">
<label for="{{form.name.id_for_label}">Centre Name</label>
<input type="text" placeholder="Centre Name" name="name" maxlength="250" id="id_name" style="box-sizing: border-box; width:500px;">
</div>
</div>
<div class="form-group col col-md-3" style="float:right; margin-top=-80px;width=200%">
<label for="{{form.address.id_for_label}" style="margin-left:200px;width:200%;white-space:nowrap;">Centre Address</label>
<input type="text" placeholder="Centre Address" name="address" maxlength="250" id="id_address" style="width:500px; margin-left:200px;">
</div>
</div>
<br> <br><br><br>
<div class="col col-md-12">
<div class="form-group col col-md-3" style="float:right; margin-top=-80px;">
<label for="{{form.contact.id_for_label}" style="margin-left:200px;width:200px;white-space:nowrap;">Contact Person</label>
<input type="text" placeholder="Contact Person" name="address" maxlength="250" id="id_contact" style="width:500px; margin-left:200px;">
</div>
{{ user_form.non_field_errors }}
<div class="fieldWrapper" >
<div class="form-group col col-md-3" >
<label for="{{form.phone.id_for_label}" style="white-space:nowrap;">Contact Number</label>
<input type="text" name="phone" maxlength="10" id="id_phone" placeholder="Contact Number" style="width:500px";>
{{ form.phone.errors }}
</div>
</div>
</div>
<br>
<br>
<div class="col col-md-12" style="padding-left:4.5% ;padding-top:2%">
<input type="submit" value="Save" class="btn btn-primary" style=" height:30px;width:80px;padding-bottom:2em;"></input>
</div>
</form>
You have the wrong name attribute for the contact field, as a result of which it is not being submitted. At the same time, you are not outputting errors for that field.
(Note, you really should use the Django form tags to output the input elements; that would have avoided this situation, as well as pre-populating the fields when the template is redisplayed after validation.)

ValueError at /accounts/upload_save/

I got an error,ValueError at /accounts/upload_save/
The view accounts.views.upload_save didn't return an HttpResponse object. It returned None instead.
Always image cannot be sent normally. I wrote in views.py
def photo(request):
d = {
'photos': Post.objects.all(),
}
return render(request, 'registration/accounts/profile.html', d)
def upload_save(request):
if request.method == "POST":
print(444)
form = UserImageForm(request.POST, request.FILES)
if form.is_valid():
print(5555)
image1 = form.cleaned_data.get('image1')
image2 = form.cleaned_data.get("image2")
user = request.user
ImageAndUser.objects.create(
User=user,
image=image1,
image2=image2,
image3=image3,
)
return redirect('registration/accounts/photo.html')
else:
print(666)
form = UserImageForm(request.POST or None)
return render(request, 'registration/profile.html',{'form':form})
in profile.html
<main>
<div>
<img class="absolute-fill">
<div class="container" id="photoform">
<form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data" role="form">
{% csrf_token %}
  <div class="input-group">
<label>
<input id="image1" type="file" name="image1" accept="image/*" style="display: none">
</label>
    <input type="text" class="form-control" readonly="">
  </div>
  <div class="input-group">
<label>
<input id="image2" type="file" name="image2" accept="image/*" style="display: none">
</label>
    <input type="text" class="form-control" readonly="">
  </div>
  
  <div class="input-group">
<label>
<input id="image3" type="file" name="image3" accept="image/*" style="display: none">
</label>
    <input type="text" class="form-control" readonly="">
  </div>
<div class="form-group">
<input type="hidden" value="{{ p_id }}" name="p_id" class="form-control">
</div>
<input id="send" type="submit" value="SEND" class="form-control">
</form>
</div>
</div>
</div>
</main>
in forms.py
class UserImageForm(forms.ModelForm):
image = forms.ImageField()
class Meta:
model = ImageAndUser
fields = ('image1','image2','image3')
in urls.py
urlpatterns = [
url(r'^profile/$', views.profile, name='profile'),
url(r'^photo/$', views.photo, name='photo'),
url(r'^upload_save/$', views.upload_save, name='upload_save'),
]
I really cannot understand why this error happens.I surely send images so I think type is not None.What is wrong in my code?How should I fix this?I debuged my views.py code,so 444 is shown in print(444).Traceback is
Traceback:
File "/Users/xxx/anaconda/envs/py35/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/Users/xxx/anaconda/envs/py35/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
198. "returned None instead." % (callback.__module__, view_name)
Exception Type: ValueError at /accounts/upload_save/
Exception Value: The view accounts.views.upload_save didn't return an HttpResponse object. It returned None instead.
couple of thing wrong in your code:
First you model looks like this:
Modle: ImageAndUser contain four fieds: user, image, image2, image3
as you have mentioned in object creation.
ImageAndUser.objects.create(User=user,image=image1,image2=image2,image3=image3
)
and you mentioned field in form:
class UserImageForm(forms.ModelForm):
image = forms.ImageField()
class Meta:
model = ImageAndUser
fields = ('image1','image2','image3')
where image1 is coming from. It's image attribute.
do it like this.
class UserImageForm(forms.ModelForm):
class Meta:
model = ImageAndUser
fields = ('image','image2','image3')
Make Edit in your template side.
<input id="image" type="file" name="image" accept="image/*" style="display: none">
</label>
   
Hope this works.
For one thing, image3 is not being set. Try adding this line
image3 = form.cleaned_data.get("image3")
after the one that does the same thing for image2.
Further to that, the view will return None if the form is invalid, i.e. if form.is_valid() returns False.

Django User Form don't save on database

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.

Categories

Resources