How to get the Jinja2 generated input value data? - python

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

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

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

flask, pymongo, forms - loading pymongo data into a form for editing

What I am trying to achieve:
I am trying to build a very simple admin interface from scratch that stores text fields and images in a mongodb. The user can then login and make small changes to the content of the site.
My issue and where I think I am confused:
Is it possible in pymongo to generate forms with the existing db records showing (so they can be edited and updated in the db)? After trying to understand the problem, I think my confusion lies whether or not I can use WTForms with pymongo directly or if I need to use object based mappers, such as MongoEngine.
Here is my flask app:
app = Flask(__name__)
# define the mongo connection
app.config['DB_HOST'] = 'mongodb://localhost/'
app.config['DB_PORT'] = 27017
app.config['DB_DBNAME'] = 'my_db'
the_db = PyMongo(app, config_prefix='DB')
#others routes here...
#app.route("/admin/")
def dashboard():
pages = list(the_db.db.pages.find({}))
return render_template('admin.html', pages=pages)
#app.route('/admin/update', methods=['POST'])
def update():
updated = datetime.datetime.utcnow()
page = request.form['page_name']
header = request.form['header']
body = request.form['body']
h_db.db.pages.update_one(
{'page': page},
{'$set':
{
'updated': updated,
'header': header,
'body': body
}
}, upsert=True)
pages = list(the_db({}))
return render_template('admin.html', pages=pages)
Here is the template:
{% for i in pages %}
{{ i.page }}<br>
{% endfor %}
{% from "_formhelpers.html" import render_field %}
<form action="/admin/update" autocomplete="on" method="POST">
{{ render_field(form.username) }}
<input type="text" name="page_name" /><br/>
<input type="text" name="header" /><br/>
<input type="TextAreaField" name="body" /><br/>
<input type="submit" name="submit" /><br/>
</form>
This is actually really simple. If you look at the HTML docs for forms then you'll find you can do something like:
<input type="text" name="firstname" value="Mickey"><br>
And "Mickey" will show up in the form for you. So, with flask all you need to do is declare variables in the server code that holds values from your mongodb call for the route and then pass them to the template like you do with "pages" Then in the front end you can render this dynamically with embedded python in Jinja, something like:
#app.route("/admin/<int:page>")
def dashboard(page):
pages = the_db.db.pages.find({page})
for p in pages:
page_name = [p['page']]
header = [p['header']]
body = [p['body']]
return render_template('admin.html', page_name=page_name, header=header, body=body)
Then you can take your template and embed like:
<form action="/admin/update" autocomplete="on" method="POST">
{{ render_field(form.username) }}
<input type="text" name="page_name" value={{ page_name|string }}/><br/>
<input type="text" name="header" value={{ header|string }}/><br/>
<input type="TextAreaField" name="body" value={{ body|string }}/><br/>
<input type="submit" name="submit" /><br/>
</form>
I'm not a WTForms expert, so I'm probably bypassing some helpers that it offers, but for the most part the basics are here. Summarizing:
You need to parse the elements of the MongoDB document and pass them to the template. You can use Jinja's power of dynamically rendering these values to the front-end IN THE APPROPRIATE PLACE as outlined by the HTML standard (the "values" placeholder in the elements). This will get you what you want at it's most basic.
If you want to get fancy you can look at AngularJS to handle the front-end MVC and you can visualize your edits on the fly before submission...sort of like what you see here on SO.com where your post shows up live beneath the edit box.

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.

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