I would like to render a Django form in the following manner...
Form UI
In particular, how would I go about populating and rendering the three drop-down lists based on the model provided.
The model
class Positions(models.Model):
position_code = models.CharField(primary_key=True, max_length=8)
name = models.CharField(max_length=64, blank=True, null=True)
description = models.CharField(max_length=4000, blank=True, null=True)
position_type = models.CharField(max_length=8, blank=True, null=True)
class Meta:
managed = False
db_table = 'positions'
class Clubs(models.Model):
club_id = models.AutoField(primary_key=True)
short_name = models.CharField(max_length=4, blank=True, null=True)
club_name = models.CharField(max_length=4000, blank=True, null=True)
nickname = models.CharField(max_length=4000, blank=True, null=True)
class Meta:
managed = False
db_table = 'clubs'
class Players(models.Model):
player_id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=512, blank=True, null=True)
last_name = models.CharField(max_length=512, blank=True, null=True)
dob = models.CharField(max_length=512, blank=True, null=True)
display_name = models.CharField(max_length=512, blank=True, null=True)
active = models.BooleanField(default=True)
class Meta:
managed = False
db_table = 'players'
class DefaultSquads(models.Model):
default_squad_id = models.AutoField(primary_key=True)
club = models.ForeignKey(Clubs, models.DO_NOTHING)
player = models.ForeignKey('Players', models.DO_NOTHING)
position_code = models.ForeignKey('Positions', models.DO_NOTHING, db_column='position_code', blank=True, null=True)
playing_status_code = models.CharField(max_length=16, blank=True, null=True)
class Meta:
managed = False
db_table = 'default_squads'
The view
class DefaultSquadsViewCreate(CreateView):
template_name = 'fafl/defaultSquad_form.html'
model = DefaultSquads
fields = ['player', 'position_code', 'playing_status_code']
success_url = reverse_lazy('fafl:defaultSquads-list')
def get_context_data(self, **kwargs):
context = super(DefaultSquadsView, self).get_context_data(**kwargs)
context['clubs'] = Clubs.objects.all().order_by('club_id')
context['players'] = Players.objects.all().order_by('player_id')
return context
The template
<form method="POST" class="form-horizontal">
{% csrf_token %}
<div class="box-body">
<div class="form-group">
<label for="{{ form.club.club_id.id_for_label }}" class="col-sm-2 control-lable">Club</label>
<div class="col-sm-10">
<!-- Not sure how ? -->
<select id="{{ form.club.club_id.id_for_label }}" name="club" class="form-control">
<option value="None"></option>
{% for club in clubs %}
<option value="{{ club.club_id }}" selected="selected">{{ club.nickname }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<label for="{{ form.club_name.id_for_label }}" class="col-sm-2 control-lable">Player</label>
<div class="col-sm-10">
<input id="{{ form.short_name.id_for_label }}" type="text" name="short_name" maxlength="100" class="form-control" required />
</div>
</div>
<div class="form-group">
<label for="{{ form.club_name.id_for_label }}" class="col-sm-2 control-lable">Position</label>
<div class="col-sm-10">
<input id="{{ form.nickname.id_for_label }}" type="text" name="nickname" maxlength="6" class="form-control" required />
</div>
</div>
</div>
<div class="box-footer">
<div class="margin">
<button type="button" class="btn btn-danger pull-right" data-toggle="modal" data-target="#myModal"><i class="fa fa-trash" role="button"></i> Delete</button>
Cancel
<button type="submit" class="btn btn-success"><i class="fa fa-check" role="button"></i> Save</button>
</div>
</div>
</form>
Since your question was only directed to form rendering . . .
In the view:
class DefaultSquadsViewCreate(CreateView):
template_name = 'fafl/defaultSquad_form.html'
model = DefaultSquads
fields = ['player', 'position_code', 'playing_status_code']
success_url = reverse_lazy('fafl:defaultSquads-list')
def get_context_data(self, **kwargs):
context = super(DefaultSquadsView, self).get_context_data(**kwargs)
context['clubs'] = Clubs.objects.all().order_by('club_id')
context['players'] = Players.objects.all().order_by('player_id')
context['positions'] = Positions.objects.all()
return context
In the template:
<div class="form-group">
<label for="{{ form.club.id_for_label }}" class="col-sm-2 control-label">Club</label>
<div class="col-sm-10">
<select id="{{ form.club.id_for_label }}" name="{{ form.club.html_name }}" class="form-control">
<option value="" selected>None</option>
{% for club in clubs %}
<option value="{{ club.club_id }}">{{ club.nickname }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<label for="{{ form.player.id_for_label }}" class="col-sm-2 control-label">Player</label>
<div class="col-sm-10">
<select id="{{ form.player.id_for_label }}" name="{{ form.player.html_name }}" class="form-control">
<option value="" selected>Please select a player</option>
{% for player in players %}
<option value="{{ player.player_id }}">{{ player.display_name }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<label for="{{ form.postion_code.id_for_label }}" class="col-sm-2 control-label">Position Code</label>
<div class="col-sm-10">
<select id="{{ form.position_code.id_for_label }}" name="{{ form.position_code.html_name }}" class="form-control">
<option value="" selected>Please select a Position</option>
{% for position in positions %}
<option value="{{ position.position_code }}">{{ position.name }}</option>
{% endfor %}
</select>
</div>
</div>
Related
I am newbie to Python and Django.
I'm using DAL on a form inside a Bootstrap modal. Clicking the dropdown list appears behind the modal. The autocomplete function works correctly if I do it outside of the modal.
I'm using:
Django: 4.0.5
django-autocomplete-light: 3.9.4
Bootstrap 5.2.2
Python 3.10.4
To try to fix it, I have created a style.css file with the following code, as indicated in:
bootstrap modal with select2 z-index
.select2-container {
z-index: 9999 !important;
}
Now the list appears in front of the modal, but it doesn't allow typing in the search box. I've tried doing the following, but it doesn't work:
https://select2.org/troubleshooting/common-problems
$(document).ready(function() {
$("#codigo_emplazamiento").select2({
dropdownParent: $("#FormularioCrear")
});
});
I've tried removing tabindex="-1" from the modal, but it doesn't work.
It seems to be related to this, but I can't get it to work:
https://lightrun.com/answers/yourlabs-django-autocomplete-light-search-input-not-receiving-focus
This is my code:
forms.py
class FormularioTarea(forms.ModelForm):
class Meta:
model = Tarea
fields = ['referencia_interna', 'codigo_emplazamiento', 'estado', 'fecha_fin', 'tipo_documento']
autocomplete.ModelSelect2(url='emplazamientoautocompletar')})
widgets = {
'codigo_emplazamiento': autocomplete.Select2(
url='emplazamientoautocompletar',
)
}
models.py
class Emplazamiento(models.Model):
TIPO_ELECCION = (('URB', 'Urbano'), ('RUR', 'Rural'))
codigo_emplazamiento = models.CharField(unique=True, max_length=10)
direccion = models.CharField(max_length=254)
municipio = models.ForeignKey(Municipio, on_delete=models.PROTECT)
ref_catastral = models.CharField(max_length=14, blank=True)
tipo_emplazamiento = models.CharField(max_length=15, choices=TIPO_ELECCION)
latitud = models.DecimalField( blank=True, null=True, decimal_places=10, max_digits=13)
longitud = models.DecimalField( blank=True, null=True, decimal_places=10, max_digits=13)
def save(self, *args, **kwargs):
self.codigo_emplazamiento = self.codigo_emplazamiento.upper()
return super(Emplazamiento, self).save(*args, **kwargs)
class Meta:
ordering =('-id',)
def __str__(self):
return (self.codigo_emplazamiento)
class Tarea(models.Model):
referencia_interna = models.CharField(max_length=20, unique=True)
codigo_comparticion = models.CharField(max_length=20, unique=True, blank=True, null=True)
ESTADOS_DE_TAREA = (('PENDIENTE', 'Pendiente'), ('EN_CURSO', 'En Curso'), ('FINALIZADO', 'Finalizado'))
codigo_emplazamiento = models.ForeignKey(Emplazamiento, on_delete=models.PROTECT)
estado = models.CharField(max_length=15, choices=ESTADOS_DE_TAREA)
SELECCION_DE_DOCUMENTOS = (('PROYECTO', 'Proyecto'), ('ANEXO', 'Anexo'), ('PEP', 'Pep'))
tipo_documento = models.CharField(max_length=15, choices=SELECCION_DE_DOCUMENTOS)
fecha_entrada = models.DateField(auto_now_add=True)
fecha_fin = models.DateField(blank=True, null=True)
class Meta:
ordering =('-id',)
def __str__(self):
return (self.referencia_interna + ' - ' + str(self.id))
urls.py
urlpatterns = [
path('emplazamientos/autocompletar', EmplazamientoAutocomplete.as_view(), name = 'emplazamientoautocompletar'),
]
views.py
class EmplazamientoAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
#if not self.request.user.is_authenticated:
# return Country.objects.none()
qs = Emplazamiento.objects.all()
if self.q:
qs = qs.filter(codigo_emplazamiento__icontains=self.q)
return qs
Modal in Template:
<div class="modal fade" id="FormularioCrear" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">{{ titulocreador }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body" id="CuerpoModal">
<form method="POST" enctype="multipart/form-data" action=" {% url 'creatarea' %}">
{% csrf_token %}
{{ formulario.as_p }}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary">Crear</button>
</form>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#codigo_emplazamiento").select2({
dropdownParent: $("#FormularioCrear")
});
});
</script>
Modal in rendered template:
<div class="modal fade" id="FormularioCrear" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Crea nueva Tarea</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body" id="CuerpoModal">
<form method="POST" enctype="multipart/form-data" action=" /proyectos/tareas/crear/">
<input type="hidden" name="csrfmiddlewaretoken" value="kWogOGY57TUQv49PCR5CroMbEmpMiM5qNUC17gTI6gPZjrq3riiuiXrhm2STNuTk">
<p>
<label for="id_referencia_interna">Referencia interna:</label>
<input type="text" name="referencia_interna" maxlength="20" required id="id_referencia_interna">
</p>
<p>
<label for="id_codigo_emplazamiento">Codigo emplazamiento:</label>
<select name="codigo_emplazamiento" required id="id_codigo_emplazamiento" data-autocomplete-light-url="/proyectos/emplazamientos/autocompletar" data-autocomplete-light-function="select2" data-autocomplete-light-language="es">
</select>
</p>
<p>
<label for="id_estado">Estado:</label>
<select name="estado" required id="id_estado">
<option value="" selected>---------</option>
<option value="PENDIENTE">Pendiente</option>
<option value="EN_CURSO">En Curso</option>
<option value="FINALIZADO">Finalizado</option>
</select>
</p>
<p>
<label for="id_fecha_fin">Fecha fin:</label>
<input type="text" name="fecha_fin" id="id_fecha_fin">
</p>
<p>
<label for="id_tipo_documento">Tipo documento:</label>
<select name="tipo_documento" required id="id_tipo_documento">
<option value="" selected>---------</option>
<option value="PROYECTO">Proyecto</option>
<option value="ANEXO">Anexo</option>
<option value="PEP">Pep</option>
</select>
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary">Crear</button>
</form>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#codigo_emplazamiento").select2({
dropdownParent: $("#FormularioCrear")
});
});
</script>
The problem is modal focus, so if you review the documentation https://getbootstrap.com/docs/5.3/components/modal/#options in options there's a definition for the focus. So at the end you just need to add data-bs-focus="false" to your modal definition.
...
I'm trying to save the data from a form by POST method. When i try to save in vars at views.py it put inside none
here i show important parts of my code:
add.html:
<form method="POST">
{% csrf_token %}
<h5>AÑADIR PEDIDO</h5>
<div class="form-group">
<label for="cliente">Nombre del Cliente</label>
<input type="text" class="form-control" id="cliente" placeholder="pepito" />
</div>
<div class="form-group">
<label for="producto">Codigo del Producto</label>
<select class="form-control" id="producto">
{% for cantidades in cantidad_pedido %}
<option value="{{cantidades.Cproducto}}">
{{cantidades.Cproducto}}
</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="cantidad">Cantidad de dicho producto</label>
<input type="number" class="form-control" id="cantidad" placeholder="cantidad" />
</div>
<button type="submit" class="btn btn-dark" style="margin-bottom: 1%;">Añadir!</button>
</form>
models.py:
class Stock(models.Model):
Cproducto = models.CharField(max_length=50, primary_key=True)
cantidad = models.IntegerField()
class Pedido(models.Model):
Cpedido = models.CharField(max_length=50, primary_key=True)
Ccliente = models.CharField(max_length=50)
FechaPedido = models.DateField(default=datetime.now)
class detallePedido(models.Model):
Cpedido = models.ForeignKey(Pedido, on_delete=models.CASCADE)
Cproducto = models.ForeignKey(Stock, on_delete=models.CASCADE)
Cantidad = models.IntegerField()
views.py :
def add(request):
cantidad_pedido = Stock.objects.all()
if request.POST:
client = request.POST.get('cliente')
producto = request.POST.get('producto')
cantidad = request.POST.get('cantidad')
stock_producto = Stock.objects.get(Cproducto=producto)
if(cantidad > stock_producto.cantidad):
messages.error(request, 'Error, la cantidad es mayor')
return render(request, 'add.html', {'cantidad_pedido': cantidad_pedido})
and here one picture of the vars:
You are missing as mention above in comment
I think you are making request with id attribute but instead of id you need to do with name attribute like this
form method="POST">
{% csrf_token %}
<h5>AÑADIR PEDIDO</h5>
<div class="form-group">
<label for="cliente">Nombre del Cliente</label>
<input type="text" class="form-control" name="cliente" placeholder="pepito" />
</div>
<div class="form-group">
<label for="producto">Codigo del Producto</label>
<select class="form-control" name="producto">
{% for cantidades in cantidad_pedido %}
<option value="{{cantidades.Cproducto}}">
{{cantidades.Cproducto}}
</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="cantidad">Cantidad de dicho producto</label>
<input type="number" class="form-control" name="cantidad" placeholder="cantidad" />
</div>
<button type="submit" class="btn btn-dark" style="margin-bottom: 1%;">Añadir!</button>
</form>
and you can use both id and name but for making request you need to name attribute
So, I have the following in my models.py:
UNITY_CHOICES = (
('g', 'Gram(s)'),
('kg', 'Kilogram(s)'),
('l', 'Liter(s)'),
('cl', 'Centiliter(s)'),
)
class Recipe_Ingredient(models.Model):
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
quantity = models.FloatField()
cost = models.DecimalField(max_digits=20, decimal_places=2)
quantityUnit = models.CharField(
max_length=2,
choices=UNITY_CHOICES,
default=GRAM,
)
class Ingredient(models.Model):
name = models.CharField(max_length=200)
articleNumber = models.IntegerField(unique=True)
costPrice = models.DecimalField(max_digits=20, decimal_places=2)
costAmout = models.FloatField()
costUnity = models.CharField(
max_length=2,
choices=UNITY_CHOICES,
default=GRAM,
)
And I have a simple form to add this model to my database:
class Recipe_IngredientForm(forms.ModelForm):
class Meta:
model = Recipe_Ingredient
fields = ('quantity', 'quantityUnit', 'ingredient')
So I was wondering if there's a way of filtering the quantityUnit available choices depending on the ingredient chosen.
I'll try to make it clear by an example: Let's say I choose to add Potato and the costUnity for Potato is 'g', then I want to make 'kg' and 'g' the only choices for quantityUnit. Is that a good example? I can try to think of something better if it's not clear enough.
Anyway, is it possible to do such thing? Thanks.
UPDATE:
forms.py:
class Recipe_IngredientForm(forms.ModelForm):
class Meta:
model = Recipe_Ingredient
fields = ('quantity', 'quantityUnit', 'ingredient')
template:
{% extends 'recipe/base.html' %}
{% block content %}
<h1>Add Ingredient to Recipe</h1>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}
Rendered HTML:
<h1>Add Ingredient to Recipe</h1>
<form method="POST" class="post-form"><input type="hidden" name="csrfmiddlewaretoken" value="tXVR3NM1R4TBwOJArWWClL71r8S5C18gWKz9mKK42wlEamf6NcBjzrieF5dQBOaO">
<p>
<label for="id_quantity">Quantity:</label>
<input type="number" name="quantity" required="" id="id_quantity" step="any">
</p>
<p>
<label for="id_quantityUnit">QuantityUnit:</label>
<select name="quantityUnit" id="id_quantityUnit">
<option value="g" selected="">Gram(s)</option>
<option value="kg">Kilogram(s)</option>
<option value="l">Liter(s)</option>
<option value="cl">Centiliter(s)</option>
</select>
</p>
<p>
<label for="id_ingredient">Ingredient:</label> <select name="ingredient" required="" id="id_ingredient">
<option value="" selected="">---------</option>
<option value="1">Carrot</option>
<option value="2">Potato</option>
<option value="3">Water</option>
<option value="4">Juice</option>
</select>
</p>
<button type="submit" class="save btn btn-default">Save</button>
</form>
I've been working on an application I originally started in Django 1.7, then ported it over to 1.10, where it stopped working. It will work if I select a District to search by, but only by the District. What I'm hoping is that if all the search terms are left blank, it will return all objects in that pool. It would be great if anyone had some ideas on where this is going wrong, as it doesn't give me errors, just tells me there are no results.
Model:
class PlantingSite(models.Model):
id_planting_site = models.IntegerField(null=True, blank=True)
empty = models.BooleanField(default=False)
address = models.CharField(max_length=256, null=True, blank=True)
street = models.CharField(max_length=256, null=True, blank=True)
coord_lat = models.CharField(max_length=256, null=True, blank=True)
coord_long = models.CharField(max_length=256, null=True, blank=True)
zipcode = models.CharField(max_length=256, null=True, blank=True)
neighborhood = models.ForeignKey(Neighborhood, null=True)
district = models.ForeignKey(District, null=True)
property_address = models.CharField(max_length=256, null=True, blank=True)
property_street = models.CharField(max_length=256, null=True, blank=True)
property_zipcode = models.CharField(max_length=256, null=True, blank=True)
property_owner = models.ForeignKey(Contact, related_name='planting_sites_owned_by_contact', null=True)
contact = models.ForeignKey(Contact, related_name='planting_sites_cared_for_by_contact', null=True)
notes = models.TextField(null=True, blank=True)
basin_type = models.ForeignKey(BasinType, related_name='planting_sites_with_basin_type', null=True)
overhead_utility = models.ManyToManyField(OverheadUtility, related_name='planting_sites_with_overhead_utility', blank=True)
hardscape_damage = models.ManyToManyField(HardscapeDamage, related_name='planting_sites_with_hardscape_damage', blank=True)
aspect = models.ForeignKey(Aspect, null=True)
sequence = models.IntegerField(null=True, blank=True)
side = models.CharField(max_length=256, null=True, blank=True)
size = models.CharField(max_length=256, null=True, blank=True)
created_by = models.ForeignKey(User, related_name='planting_sites_created', null=True)
created_at = models.DateTimeField(default=timezone.now)
last_edited = models.DateTimeField(null=True, blank=True)
def __unicode__(self):
return unicode(self.id_planting_site)
class Meta:
ordering = ['-created_at']
My View:
def uf_search(request):
if request.POST:
search_sent = True
# SEARCH PLANTING SITES
if request.POST.get('search_type_id') == "1":
planting_site_search = True
if request.POST.get('address_range'):
if request.POST.get('address_start') and request.POST.get('address_end'):
address_start = request.POST.get('address_start')
address_end = request.POST.get('address_end')
r_address = Q(address__range=[address_start, address_end])
else:
r_address = Q(address__isnull=False) | Q(address__isnull=True)
elif request.POST.get('address_exact'):
if request.POST.get('address'):
address = request.POST.get('address')
r_address = Q(address__icontains=address)
else:
r_address = Q(address__isnull=False) | Q(address__isnull=True)
planting_site_fields = {
'street': request.POST.get('street'),
'zipcode': request.POST.get('zipcode'),
}
r_objects = Q()
if request.POST.get('neighborhood_id'):
r_neighborhood = Q(neighborhood__id_neighborhood=request.POST.get('neighborhood_id'))
else:
r_neighborhood = Q(neighborhood__id_neighborhood__isnull=False) | Q(neighborhood__id_neighborhood__isnull=True)
if request.POST.get('district_id'):
r_district = Q(district__id_district=request.POST.get('district_id'))
else:
r_district = Q(district__id_district=False) | Q(district__id_district=True)
for field, value in planting_site_fields.iteritems():
if value:
r_objects = Q(**{field+'__icontains': value})
if request.POST.get('empty_planting_sites'):
search_results = PlantingSite.objects.values('id', 'id_planting_site', 'address', 'street', 'zipcode', 'neighborhood__name', 'district__name', 'empty').filter(r_address, r_objects, r_neighborhood, r_district, empty=True)
else:
search_results = PlantingSite.objects.values('id', 'id_planting_site', 'address', 'street', 'zipcode', 'neighborhood__name', 'district__name', 'empty').filter(r_address, r_objects, r_neighborhood, r_district)
request.session['search_results'] = list(search_results)
neighborhood_list = Neighborhood.objects.all()
district_list = District.objects.all()
species_list = Species.objects.all()
condition_list = TreeCondition.objects.all()
args = {'search_sent': search_sent, 'planting_site_search': planting_site_search, 'search_results': search_results, 'neighborhood_list': neighborhood_list,
'district_list': district_list, 'species_list': species_list, 'condition_list': condition_list}
args.update(csrf(request))
return render(request, 'uf_search.html', args)
Template:
<form action="/forest/search/" method="post">
{% csrf_token %}
<input type="hidden" name="search_type_id" id="search_type_id" value="1">
<p>
<div class="row">
<div class="col-sm-4">
Address:
</div>
<div class="col-sm-4">
Exact: <input type="checkbox" name="address_exact" id="address_exact" />
</div>
<div class="col-sm-4">
Range: <input type="checkbox" name="address_range" id="address_range" />
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
Range:
</div>
<div class="col-sm-8">
<input type="text" id="address_start" name="address_start" /> to <input type="text" id="address_end" name="address_end" />
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
Exact:
</div>
<div class="col-sm-8">
<input type="text" id="address" name="address" />
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
Street:
</div>
<div class="col-sm-8">
<input type="text" id="street" name="street" />
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
Zipcode:
</div>
<div class="col-sm-8">
<input type="text" id="zipcode" name="zipcode" />
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
Neighborhood:
</div>
<div class="col-sm-8">
<select name="neighborhood_id" id="neighborhood_id">
<option value="">Select:</option>
{% for neighborhood in neighborhood_list %}
<option value="{{neighborhood.id_neighborhood}}">{{neighborhood.name}}</option>
{% endfor %}
</select>
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
District:
</div>
<div class="col-sm-8">
<select name="district_id" id="district_id">
<option value="">Select:</option>
{% for district in district_list %}
<option value="{{district.id_district}}">{{district.name}}</option>
{% endfor %}
</select>
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
</div>
<div class="col-sm-8">
<input type="checkbox" name="empty_planting_sites" id="empty_planting_sites">
Show Empty Planting Sites Only
</div>
</div>
</p>
<input type="submit" name="submit" id="submit" value="Search" />
</form>
Any ideas? Is it something that was dropped in the newest version?
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.