Make custom form manually in Django based on a model - python

I am making a basic attendance record system with following models in my models.py file : Department, Employee, Absence.
Absence model is as below:
class Absences(models.Model):
emp_id = models.ForeignKey(Employees, on_delete=models.CASCADE, null=False)
leave_date = models.DateField(null=False)
leave_type = models.ForeignKey(LeaveTypes, on_delete=models.CASCADE)
absence_added = models.DateTimeField(auto_now_add=True)
absence_updated = models.DateTimeField(auto_now=True)
Now I want to create a form that lets you select date (that will be inserted in leave_date column) and a list of all employees with a dropdown (populated with leave_type) and submit button (which once clicked with save absences to database based on Absences model above.
How do I do this?

I found the solution.
You can make insertions directly into a model by simply instantiating an object of the model's class with values you want to insert into the model's table, and then run .save() method on that object.
I wanted to make a form that could make multiple entries in Absences model (the single entry form is easy to create using CreateView class). So I created a template that had the form containing the input fields depending on the number of employees(from Employees model) who's attendance needed to be marked. Following is the code of the template's form.
<form method="POST">
{% csrf_token %}
<label for="id_leave_date">Date</label>
<input type="date" name="leave_date" class="form-control" placeholder="Select a date" required="" id="id_leave_date">
<br>
<table class="table table-hover">
<thead>
<tr>
<th>Employee</th>
<th>Absence</th>
</tr>
</thead>
<tbody>
{% for emp in emps %}
<tr>
<td>{{ emp.emp_name }}</td>
<td>
<input type="radio" name="{{ emp.pk }}" id="p{{ emp.pk }}" value="present" checked> <label for="p{{ emp.pk }}">Present</label>
{% for leave in leaves %}
<input type="radio" name="{{ emp.pk }}" id="{{ leave.pk }}{{ emp.pk }}" value="{{ leave.pk }}"> <label for="{{ leave.pk }}{{ emp.pk }}">{{ leave.leave_type }}</label>
{% endfor %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
<input type="submit" value="Mark Attendance" class="btn btn-primary">
</form>
To control the template, I created a view called mark_all_attendance(). This view showed the above mentioned template if it was accessed with a GET request and would send the template info it needed to generate form. If the view was accessed through POST request, it would process the submitted form in the template by manually accessing the key-value pairs of submitted form fields by iterating over all the pairs. On each iteration it instantiates objects of Absences class using submitted a form field set, and then running the .save() method on that object. This inserts the data in field set being iterated over into the Absences table. Then redirect the browser to a success page using HttpResponseRedirect. Following is the view code:
`def mark_all_attendance(request):
submitted = False
all_emps = models.Employees.objects.all()
leaves = models.LeaveTypes.objects.all()
if request.method == 'POST':
leave_date_from_post = datetime.datetime.strptime(request.POST['leave_date'], '%Y-%m-%d').date()
print('Original: ', request.POST['leave_date'])
print(leave_date_from_post)
for key, value in request.POST.items():
if not (key == 'csrfmiddlewaretoken' or key == 'leave_date'):
# print(key + " : " + value)
if value != 'present': #if present, don't insert record in absences table
record = models.Absences(
emp_id = models.Employees.objects.get(pk=key),
leave_type = models.LeaveTypes.objects.get(pk=value),
leave_date = leave_date_from_post
)
record.save()
return HttpResponseRedirect('/attendance/markallattendance?submitted=True')
else:
if 'submitted' in request.GET:
submitted = True
return render(request, 'attendance/markallattendance.html', {'emps': all_emps, 'leaves': leaves, 'submitted': submitted})`

Related

Multiple button in Django: Accept and Reject

I am new to Django. I am working on a project where I want accept and reject button and whenever client click on the respective button that object will go into the accept or reject template. I have no idea how can I do this.
This is my .html file which is displaying all the objects and have a accept and reject button:
<div class="body table-responsive">
<form id="form" method="POST" action = "{% url 'admin_team_detail' %}">
{% csrf_token %}
<table class="table table-hover">
<thead>
<tr>
<th>S No.</th>
<th>COMPANY NAME</th>
<th>TEAM MEMBER</th>
<th>EMAIL</th>
<th>STATUS</th>
<th><center>#</center></th>
</tr>
</thead>
<tbody>
{%for team in object%}
<tr>
<th scope="row"> {{ forloop.counter }}</th>
<td>{{team.company_name}}</td>
<td>{{team.team_member}}</td>
<td>{{team.email}}</td>
<td>-</td>
<td><center><input type="submit" value="accept" name="accept">
<input type="submit" value="reject" name="reject"></center></td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
Here is views.py:
def admin_team_detail(request):
obj= Create_Team.objects.all()
print(request.method)
if request.method == 'POST':
if 'reject' in request.POST :
Create_Team.status = 'reject'
else:
Create_Team.status = 'accept'
Create_Team.save()
return render(request, "admin/team-details.html", {"object": obj})
This is rendering all the objects from database and displaying on the website.
I know that I have to make two templates for accept and reject but I don't know how it will take the objects that have a accept or reject response.
And I also want that if client click on the button then that response will be saved in the database.
And I also want to know that whether I have to add a field in my model.py for status.
First your two buttons should send the desired value to your views.py and one hidden input in order to pass the team id
<input type="submit" value="reject" name="status">
<input type="submit" value="accept" name="status">
<input type="hidden" name="id" value={{ team.id }}>
Next, in your views.py
def admin_team_detail(request):
if request.method == 'POST':
# First, you should retrieve the team instance you want to update
team = Create_Team.objects.get(id=request.POST('id'))
# Next, you update the status
if request.POST.get('status'):
team.status = request.POST.get('status')
team.save()
Note: this example assumes your Team model has a status field in order to store the reject/accept value.
class Team(models.Model):
# You existing fields...
status = models.CharField(max_length=30)
First You need to create a form for each object inside the template.
{%for team in object%}
<form method="POST">
{%csrf_token%}
<input type="hidden" name="team_id" value={{ team.id }}>
<input type="submit" value="reject" name="status">
<input type="submit" value="accept" name="status">
</form>
{% endfor %}
Now in View.py, you need to do something like this:
def admin_team_detail(request):
if request.method == 'POST':
# I am assuming Create_Team is your model where all team's are present.
team = Create_Team.objects.get(id=request.POST.get("team_id"))
team.status = request.POST.get("status")
team.save()

How to add forms to a dictionary upon submission

I am creating a shopping cart as a part of the application I'm building.
I am trying to figure out how to add a form submission to a dictionary (I think this is what I need to do).
So for example this is what the page would look like(This is just test data).
Upon Clicking the add button I want the item name and price to populate in the Orders table to the right of the Pricing table(To start off). Once all orders have been added I'd click the Order button and that will order the added items in some type of list to the database using sqlalchemy. Now I feel strongly and I may be wrong that upon submitting form using add button that the form needs to be added to a dictionary. I just don't know how to save that dictionary and where that dictionary should be stored? Here is my code as of now.
routes.py
I tried putting the dictionary with in the route function but a single instance is created on each submission. So nothing is really being saved to dictionary.
#app.route('/equipment', methods=['POST', 'GET'])
def equipment():
form = OrderEquipmentForm()
eq = equipment_prices
# Tried to store forms in this dictionary but it look like a new instance
# is created on every form submission
ordersss = {}
if form.validate_on_submit():
ordersss[form.Type.data] = form.Price.data
print(form.Type.data, form.Price.data)
print(ordersss)
return redirect(url_for('equipment'))
return render_template('equipment.html', name='equipment', eq=eq, form=form)
#app.route('/equipment/cart', methods=['GET, POST'])
def cart():
return render_template('cart.html', name='cart')
Forms.py
Not sure if there needs to be function with in the actual form that adds the values to a dictionary
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
class AddEquipmentForm(FlaskForm):
Type = StringField('Type of Equipment',DataRequired())
Price = StringField('Price',DataRequired())
submit = SubmitField('Add equipment')
class OrderEquipmentForm(FlaskForm):
Type = StringField()
Price = StringField()
Order = SubmitField('Order')
# Should Dictionary go here?
# Not sure
def dict():
dict = {}
dict[Type] = Price
equipment.html
I would like to loop the element of the dictionary with in the Orders Table, if a dictionary is needed.
{% extends 'base.html' %}
{% block content %}
<div class="row">
<div class="col-6-sm">
<h1>Pricing</h1>
<table class='border'>
<thead class='border'>
<th style="width:200px;">Equipment</th>
<th style="width:200px; text-align:center;">Price</th>
<th></th>
</thead>
{% for quip in eq %}
<form method="post">
{{ form.hidden_tag() }}
<tr class ='border'>
<td>{{ quip }}</td>
<td style="text-align:center;"> <strong>${{ eq[quip] }}</strong></td>
<!-- Here I'm adding StringFields from the form but hiding them so they aren't displayed so I can submit the data somehow, hopefully to a dictionary. -->
<td style="display:none;">{{ form.Type(value=quip)}}</td>
<td style="display:none;">{{ form.Price(value=eq[quip]) }}</td>
<td><button class='btn btn-primary' type="submit">Add</button></td>
</tr>
</form>
{% endfor %}
</table>
</div>
<div class="col-6-sm">
<h1>Orders</h1>
<table>
<!-- This is where a loop of the dictionary elements of the items added would go -->
<tr>
<td></td>
<td></td>
</tr>
<button style='float:right' type="button" name="button" class='btn btn-info'>Order</button>
</table>
</div>
</div>
{% endblock %}

Change existing model data with form

I am trying to implement a view that displays a form to capture data and a table with the captured data of a user. The table has a form with two buttons per row, either submitting "change" or "delete" together with the object id of the object in the given table row, using POST.
My Django view looks like this:
def captureData(request):
form = MyForm(request.POST or None)
if request.method == "POST":
if 'delete' in request.POST:
# User hits "Delete" button in displayed objects table.
try:
del_object = MyObject.objects.filter(user = request.user).get(id = request.POST['delete'])
del_object.delete()
except:
# Do something ...
return redirect('captureData')
elif 'change' in request.POST:
# User hits "Change" button in displayed objects table.
ch_object = MyObject.objects.filter(user = request.user).get(id = request.POST['change'])
form = MyForm(instance = ch_object)
if form.is_valid():
form.save()
return redirect('captureData')
else:
# New data to be added to the database.
if form.is_valid():
new_object = form.save(commit = False)
new_object.user = request.user
new_object.save()
return redirect('captureData')
objects = Object.objects.filter(user = request.user)
context = {'form': form, 'objects': objects}
return render(request, 'myTemplate.html', context)
This is how the myTemplate.html looks like:
{% extends "base.html" %}
{% block content %}
<h3>Data capturing</h3>
<p>
<!-- First form, responsible for capturing data -->
<form method="POST" action=""> {% csrf_token %}
{{form}}
<input type ='submit' value='Save'/>
</form>
</p>
<h3>Captured data</h3>
<table>
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Address</th>
<th>City</th>
<th colspan="2">Actions</th>
</tr>
</thead>
<tbody>
{% for object in objects %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{object.name}}</td>
<td>{{object.address}}</td>
<td>{{object.city}}</td>
<!-- Second form (per row), responsible for submitting a "delete" or "change" -->
<form action="" method="POST">{% csrf_token %}
<td>
<button type="submit" value="{{object.id}}" name="change" id="object{{object.id}}">Change</button>
</td>
<td>
<button type="submit" value="{{object.id}}" name="delete" id="object{{object.id}}">Delete</button>
</td>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
The "delete" part works fine. The problem is the "change" part. It successfully populates the form with the selected objects data, but when I hit the capture from submit button it runs into the else: clause resulting in a new data row or an error, if the data already exists. The reason for this is obvious: The new POST data does not contain the "change" marker anymore.
How can I separate the elif: part from the else: part?

How to get the Jinja2 generated input value data?

In my HTML file, I have:
<table>
{% for user in user_data_html %}
<tr>
<td>
<input id="firstname" name="firstname" type="text" value='{{ user.FirstName }}' />
</td>
<td>
<input name="submit" type="submit" value='update' />
</td>
</tr>
{% else %}
<tr><td>no user found</td></tr>
{% endfor %}
</table>
I want to modify the user name in the webpage by clicking update button in each row. But I always get the first "firstname" using the following python code in the backend:
firstname = request.form['firstname']
How can I solve this problem?
Forms get confused when you use the same name for each input name. You could either create a separate form around each table cell with the first name or you can use the jinja2 loop index to create unique input names...
<input id="firstname{{ loop.index }}" name="firstname{{ loop.index }}" type="text" value='{{ user.FirstName }}' />
Hope this helps!
request.form is a werkzeug.datastructures.MultiDict. You can get out all the values for a field with its getlist method:
a_firstname = request.form['firstname']
all_firstnames = request.form.getlist('firstname')
If you need the names to be in the order they were defined in the form you need to subclass flask.Request and set its parameter_storage_class to an instance of ImmutableOrderedMultiDict. Then you need to set the request_class field on your Flask instance:
from flask import Flask, Request
from werkzeug.datastructures import ImmutableOrderedMultiDict
class OrderedRequest(Request):
parameter_storage_class = ImmutableOrderedMultiDict
app = Flask(__name__)
app.request_class = OrderedRequest
Then request.form.getlist('firstname') will return the fields in the order the browser sent them (which is conventionally in the order they are defined in the HTML).

Django - taking values from POST request

I have the following django template (http://IP/admin/start/ is assigned to a hypothetical view called view):
{% for source in sources %}
<tr>
<td>{{ source }}</td>
<td>
<form action="/admin/start/" method="post">
{% csrf_token %}
<input type="hidden" name="{{ source.title }}">
<input type="submit" value="Start" class="btn btn-primary">
</form>
</td>
</tr>
{% endfor %}
sources is the objects.all() of a Django model being referenced in the view. Whenever a "Start" submit input is clicked, I want the "start" view to use the {{ source.title}} data in a function before returning a rendered page. How do I gather information POSTed (in this case, in the hidden input) into Python variables?
Read about request objects that your views receive: https://docs.djangoproject.com/en/dev/ref/request-response/#httprequest-objects
Also your hidden field needs a reliable name and then a value:
<input type="hidden" name="title" value="{{ source.title }}">
Then in a view:
request.POST.get("title", "")
If you need to do something on the front end you can respond to the onsubmit event of your form. If you are just posting to admin/start you can access post variables in your view through the request object. request.POST which is a dictionary of post variables
For django forms you can do this;
form = UserLoginForm(data=request.POST) #getting the whole data from the user.
user = form.save() #saving the details obtained from the user.
username = user.cleaned_data.get("username") #where "username" in parenthesis is the name of the Charfield (the variale name i.e, username = forms.Charfield(max_length=64))
You can use:
request.POST['title']
it will easily fetch the data with that title.

Categories