I need to create a form with django to check if students are prensent or not. I can't use the 'normal' way to create a form because django want a form model implemented with every fields composing the form. I can't do this cause i don't know the number of students in a class. how can i create a dynamic form who don't care about the number of students ?
at the moemnt i created a form in the template with a for to showthe list of students with each checkbox
<form method="post">
{% csrf_token %}
Date : <input id="date" type="date" class="mt-3 mb-3">
<br>
{% for student in student_list %}
<input type="checkbox" id="student{{forloop.counter}}" name="student{{forloop.counter}}">
<label for="student{{forloop.counter}}">{{student.first_name }} {{student.last_name}}</label>
<br>
{% endfor %}
<button class="btn btn-outline-primary mr-4">Cancel</button>
<button type="submit" class="btn btn-success radius d-flex">Submit</button>
</form>
This might not be the best practice, but I think it should work.
form.html
<form method="POST">
{% csrf_token %}
Date : <input id="date" type="date" class="mt-3 mb-3">
<br>
{% for student in student_list %}
<input type="checkbox" id="student" name="student" value="1">
<label for="student">{{ student.first_name }} {{ student.last_name }}</label>
<br>
{% endfor %}
<button class="btn btn-outline-primary mr-4">Cancel</button>
<button type="submit" class="btn btn-success radius d-flex">Submit</button>
</form>
views.py
def submit_form(request)
if request.method == 'POST':
date = request.POST.get("date")
student = request.POST.getlist("student")
# TODO
EDIT :
I just named each checkbox 'student' then i get each checkbox data in view.py
call_of_roll.html
<form method="post">
{% csrf_token %}
Date : <input name="date" type="date" class="mt-3 mb-3" value="{{defaultdate|date:"Y-m-d" }}" required>
<br>
{% for student in student_list %}
<input type="checkbox" id="{{student.id}}" name="student{{student.id}}" checked>
<label for="student{{student.id}}">{{student.first_name }} {{student.last_name}}</label>
<br>
{% endfor %}
<p>Check if the student is present</p>
<div class="row">
<button class="btn btn-outline-primary mr-4">Cancel</button>
<button type="submit" class="btn btn-success radius d-flex">Submit</button>
</div>
</form>
views.py
if request.method == 'POST':
date = request.POST.get("date")
for student in students:
missing = request.POST.get('student'+str(student.id), "off")
Related
I'm trying to get values from an object of my DB on a form in html to edit it but when I call the current "value" from the attribute I get this:
Form
HTML
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
{% for campo in formulario %}
<div class="mb-3">
<label for="" class="form-label">{{ campo.label }}:</label>
{% if campo.field.widget.input_type == 'file' and campo.value %}
<br/>
<img src="{{MEDIA_URL}}/imagenes/{{campo.value}}" width="100"srcset="">
{% endif %}
<input
type="{{ campo.field.widget.input_type}}"
class="form-control"
name="{{ campo.name }}"
id=""
aria-describedby="helpId"
placeholder="{{campo.label}}"
value="{{campo.value | default:''}}"
/>
</div>
<div class="col-12 help-text"> {{campo.errors}}</div>
{% endfor %}
<input name="" id="" class="btn btn-success" type="submit" value="Enviar informacion">
</form>
Views
Models
I found the problem... I instantiate the class instead of the object
View.py
if req.method == 'POST':
df = DocumentForm.objects.filter(document_id=id)
logging.info('LOG: I am here')
if df.exists():
for d in df:
description = req.POST['{}'.format(d.description, False)]
displayName = req.POST['{}'.format(d.displayName, False)]
df.update(displayName=displayName, description=description)
return redirect('/adboard/upd')
HTML File
<form class="needs-validation" action="{{id}}" method="POST" enctype="multipart/form-data" novalidate>
{% csrf_token %}
<div class="row mt-3 mb-3"></div>
{% if messages %}
<div class="alert alert-danger" role="alert">
{% for message in messages %}
{{ message }}
{% endfor %}
</div>
{% endif %}
{% for df in data %}
<div class="form-group">
<small class="text-muted bold-label m-lower">{{{df.field}}}</small>
<label for="validationCustom01">{{df.displayName}}</label>
<input type="text" class="form-control" id="validationCustom01" name="{{df.displayName}}" value="{{df.displayName}}" placeholder="Enter Display Name">
<label for="validationCustom01">{{df.description}}</label>
<input type="text" class="form-control" id="validationCustom01" name="{{df.description}}" value="{{df.description}}" placeholder="Enter description">
<div class="invalid-feedback">
Please enter required fileds.
</div>
<!-- <div class="valid-feedback">
Looks good!
</div> -->
</div>
{% endfor %}
<button type="submit" class="btn btn-primary btn-red btn-block">SAVE</button>
</form>
What I am trying to achieve is.
Pass a variable form to the user to fill
And I get the result.
I can't tell what the input id/name would be because it's a variable.
But I am finding it difficult getting the value from the view.py file.
change
req.POST['{}'.format(d.description, False)]
to
req.POST.get('{}'.format(d.description, False))
Dear all of the Django developer community, I am facing this below issue:
I try to update a db table data which has one field and one drop down field. But I only get basic field data and not drop down list data.
I request expert help me. How can I fix this issue?
Advanced Thanks For All
views.py
def update_brands(request, id):
brand = Brand.objects.get(id=id)
form = AddBrandForms(request.POST, instance=brand)
if form.is_valid():
form.save()
return redirect('/parts/brands')
return render(request, 'parts/edit_brands.html', {'brand': brand })
edit_brands.html
{% extends 'parts/base.html' %}
{% block content %}
<form method="post" action="/parts/update_brands/{{brand.id}}/" class="post-form">
{% csrf_token %}
<div class="form-group row">
<label class="col-sm-2 col-form-label">Country Name:</label>
<div class="col-sm-4">
<input type="text" name="country" value="{{ brand.brand_name }}"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Country Name:</label>
<div class="col-sm-4">
<select id="cars" name="cars">
{% for db in dbf.all %}
<option value="{{ db.db}}">{{ db.db}}</option>
{% endfor %}
</select>
</div>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
{% endblock %}
try this
{% extends 'parts/base.html' %}
{% block content %}
<form method="post" action="/parts/update_brands/{{brand.id}}/" class="post-form">
{% csrf_token %}
<div class="form-group row">
<label class="col-sm-2 col-form-label">Country Name:</label>
<div class="col-sm-4">
<input type="text" name="country" value="{{ brand.brand_name }}"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Country Name:</label>
<div class="col-sm-4">
<select id="cars" name="cars">
{% for car in brand.all %}
<option value="{{ car }}">{{ car }}</option>
{% endfor %}
</select>
</div>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
{% endblock %}
I have problem with my code which is i try to submit my Event form in the models. But when i run the form it will show the whole form (and another thing is that it will not show the values in the select box of the rounds) and when i click on the the submit button it will through an error.Please help me out this.
VIEW SIDE CODE:--
def addevents(request):
if request.method=="POST":
name=request.POST['events']
est=request.POST['starttime']
eet=request.POST['endtime']
s=Event()
s.ename=name
s.event_start_time=est
s.event_end_time=eet
s.save()
cats = request.POST.getlist('cats')
for i in cats:
s.categories.add(Category.objects.get(id=i))
s.save()
roundd = request.POST.getlist('rround')
for j in roundd:
s.rounds.add(Round.objects.get(id=j))
s.save()
return render(request,'adminside/addevents.html')
else:
rounds = Round.objects.all()
categories = Category.objects.all()
return render(request,'adminside/addevents.html',{'categories':categories,'rounds':rounds})
MODELS SIDE:-
class Event(models.Model):
ename=models.CharField(max_length=200)
categories = models.ManyToManyField(Category)
event_data = models.DateField()
event_start_time = models.TimeField()
event_end_time = models.TimeField()
rounds = models.ManyToManyField(Round)
EVENT PAGE FORM:-
{% extends 'adminside/master.html' %}
{% block content %}
<div class="col-12">
<div class="card">
<div class="card-body">
<h4 class="card-title">Events</h4>
<p class="card-description"> All fields are Compulsory </p>
<form class="forms-sample" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="exampleInputEmail1">Add Event</label>
<input type="text" class="form-control" name="events" id="exampleInputEmail1" placeholder="Enter Event">
</div>
<div class="form-group">
<label>Categories:</label>
<select class="form-control" multiple name="cats">
{% for i in categories %}
<option value="{{ i.id }}">{{ i.cname }}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Event Start Time</label>
<input type="text" class="form-control" name="starttime" id="exampleInputEmail1" placeholder="Enter Event Start Time">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Event End Time</label>
<input type="text" class="form-control" name="endtime" id="exampleInputEmail1" placeholder="Enter Event End Time">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Round Name</label>
<select class="form-control form-control-lg" id="exampleFormControlSelect1" multiple name="rround">
{% for i in rounds %}
<option value="{{i.id}}">{{i.round}}</option>
{% endfor %}
</select>
</div>
<button type="submit" value=Addme class="btn btn-success mr-2">Submit</button>
<button class="btn btn-light">Cancel</button>
</form>
</div>
</div>
</div>
{% endblock %}
in addevents view you need to add something in event_data before saving because this value do not accept null or modify your models.py
event_data = models.DateField()
modify this to default value like the current time
event_data = models.DateField(default=timezone.now)
hope this helps
I am using the default view for logging the users.So I have not made any modelForm for it.So I am not able to provide any bootstrap class to the input fields i.e username and password. So my login form is looking ugly.Is there anyway. I want to add bootstrap class form-control to the input fields username and password.
Following is my HTML and URL snippets. All functions and classes used have their modules imported.
urls.py
url(r'^login/$', login, {'template_name': 'app/login.html'}),
login.html
<form class="form-signin" method="post"><span class="reauth-email"> </span>
{% csrf_token %}
<!--{{form.as_p}}-->
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
<!--<input class="form-control" type="email" required="" placeholder="Email address" autofocus="" id="inputEmail">-->
<!--<input class="form-control" type="password" required="" placeholder="Password" id="inputPassword">-->
<div class="checkbox">
<div class="checkbox">
<label><input type="checkbox">Remember me</label>
</div>
</div>
<button class="btn btn-primary btn-block btn-lg btn-signin" type="submit">Sign in</button>
</form>
change your login template to this
you can modify it
<div class="center-block" id="login" style="width: 40%;">
<form class="form-horizontal form" name="LoginForm" method="post">
{% csrf_token %}
{% if next %}
<input type="hidden" name="next" value="{{ next }}" />
{% endif %}
<div class="control-group">
<label class="control-label" for="username">Username</label>
<div class="controls">
<input class="form-control" type="text" id="username" name="username" placeholder="Username">
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input class="form-control" type="password" name="password" id="password" placeholder="Password">
</div>
</div><br>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-success">Login</button> or sign up
</div>
</div>
</form>
</div>
If you want to add a CSS-class, you can write a custom template filter
First, read how to make a custom template filter
https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/#writing-custom-template-filters
You'll have write here
my_app/
__init__.py
models.py
templatetags/
__init__.py
my_app_extra_filters.py # <-----------------
views.py
smth like this
my_app_extra_filters.py
from django import template
register = template.Library()
#register.filter
def add_class(modelform_input, css_class):
return modelform_input.as_widget(attrs={'class': css_class})
*if you want to know about as_widget() method, used above:
https://docs.djangoproject.com/en/1.11/ref/forms/api/#django.forms.BoundField.as_widget
then use it in the template
{% load my_app_extra_filters %}
...
{{ field.errors }}
{{ field.label_tag }}
{{ field|add_class:'bootstrap_class_name' }}
all you need is add this codes to your loginform in form.py
class AuthenticationForm(AuthenticationForm):
.
.
.
def __init__(self, *args, **kwargs):
super(UserCreationForm, self).__init__(*args, **kwargs)
for fieldname in ['username', 'password1', 'password2',]:
self.fields[fieldname].widget.attrs = {'class':'form-control'}