Django User Form don't save on database - python

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.

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

2023 Everybody! We made it. I want to update my form, but my details are not pulling through to the 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

Django return none when y try to save in vars by POST method

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

The imageField doesnt upload images django

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!

Django Templates and drop-down list

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>

Categories

Resources