Multiple button in Django: Accept and Reject - python

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

Related

Make custom form manually in Django based on a model

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

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 do I submit "POST" method forms in Django without AJAX?

I'm completely new to Django and I'm also developing a very important project in this framework with some friends. I'm having problems in submitting a "POST" method form in Django.
I'm having the "403 Forbidden" error. It says that my CSRF token isn't configured correctly. I'm pretty sure that I did setup it correctly, though.
My form is about updating an django user account in the database (MySQL). I also don't know if my program logic is right in the view. I didn't even had the opportunity to test it because of this dumb error.
The image and codes below exemplificate my problem.
My form:
<form method="POST" action="/validacao/" name="user" class="current2"> {% csrf_token %}
<table>
<tr>
<td>Nome:</td><td>
<input type='text' name='first_name' maxlength='30' value='{{usuario.first_name}}' class="campo2" />
</td>
<td>Permissão: <font style="color: red;">
{% if usuario.is_staff %} Admin {% else %} Comum {% endif %}</font>
</td>
</tr>
<tr>
<td>Sobrenome:</td>
<td><input type='text' name='last_name' maxlength='30' value='{{usuario.last_name}}' class="campo2" /></td>
</tr>
<tr>
<td>Email:</td>
<td><input type='text' name='email' maxlength='75' value='{{usuario.email}}' class="campo2"/></td>
</tr>
<tr>
<td>Senha:</td><td> <input type='password' name='password' maxlength='120' class="campo2"/></td>
</tr>
<tr>
<td>Confirmar Senha:</td><td><input type='password' name='password2' maxlength='120' class="campo2"/></td>
</tr>
<tr><td></td><td><input type='submit' name='salvar' value='Salvar' class="botao2"/></td></tr>
</table>
</form>
My view:
def validacao_perfil(request):
if request.POST:
try:
request.user.first_name = request.POST['first_name']
request.user.last_name = request.POST['last_name']
request.user.email = request.POST['email']
request.user.password = request.POST['password']
request.user.save()
validacao=1
except:
validacao=0
variaveis_resposta={ 'usuario':request.user,
'MEDIA_URL':settings.MEDIA_URL,
'height_backgroud':'900',
'rodape':'position:relative; top: 148px;',
'ordem':0,
'validacao':validacao,
'context_instance':RequestContext(request),
}
return render_to_response("perfil_usuario.html", variaveis_resposta)
Obs.: the "urls.py" is set correctly and the bizarre thing is that I can see the csrftoken cookie var using Django Debug Toolbar.
just put #csrf_exempt on your def validacao_perfil(request):, to see if this work,and also try to read the doc of django .It's very good!!

Using WTForms' populate_obj( ) method with Flask micro framework

I have a template which allows the user to edit their user information.
<form method="post">
<table>
<tr>
<td>Username:</td>
<td>{{user['username']}}</td>
</tr>
<tr>
<td>New Password:</td>
<td> <input type="password" name="password"></td>
<td>{% if form.password.errors %} {{form.password.errors}} {% endif %}<td>
</tr>
<tr>
<td>Re-enter Password:</td>
<td> <input type="password" name="confirm_password">
</td>
</tr>
<input type='hidden' name='username' value="{{user['username']}}">
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
I also have a view function for handling such edits by the user. The database I am currently using is MongoDB with the MongoKit module. I have only been able to do up to this so far in the view function, yet with no luck.
def edit():
username = request.args.get('user')
user = User.find_one({'username':username}) # Is this a correct way of doing it?
form = UserForm(**what should be placed here?**, obj=user)
if request.method == 'POST' and form.validate():
form.populate_obj(user)
user.save()
return 'updated'
return render_template('edituser.html', form=form, user=user)
I am going through populate_obj(obj) for this purpose. I couldn't find much help in this matter. What should I do in order to get populate_obj() working?
UserForm should have request.form passed into it to populate it with the values available in the POST request (if any).
form = UserForm(request.form, obj=user)
Are you using Flask-WTF? If so, check out the following sample code:
https://github.com/sean-/flask-skeleton/blob/master/skeleton/modules/aaa/views.py#L13
Specifically, you would:
def edit():
form = UserForm()
if form.validate_on_submit():
# Commit your form data
Bottom line, if you're using Flask-WTF, I'm not sure what your question is. If you aren't using Flask-WTF, use Flask-WTF.
In case of Flask-WTF, you can write like
form = UserForm(obj=user)
Thant will work!

Categories