How do I autofocus a cursor in this django form? - django

In the following template, how do I force the cursor to autofocus into the form.username field when the browser loads?
{% block content %}
<form method="post" action="">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="login" style="position: relative; left: 5em;" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
<p>Register</p>
{% endblock %}

In your forms.py define the field with the autofocus attribute:
username = forms.CharField(
label=_('Username'),
strip=True,
widget=forms.TextInput(attrs={'placeholder': _('Username'), 'class': 'form-control', 'autofocus': True})
)
https://docs.djangoproject.com/en/2.1/ref/forms/widgets/#django.forms.Widget.attrs

You can use django-widget-tweaks
<td>{{ form.username|attr:"autofocus" }}</td>
Also it can add attributes and classes, render fields with custom template and more

You could just do it with javascript (in this example, Jquery). Make sure there is a block called extra_scripts in your base.html (just above the closing </body> tag), and then add the javascript as follows:
{% block content %}
<form method="post" action="">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
...
{% endblock %}
{% block extra_scripts %}
<script type="text/javascript">
$(function () {
// When the page has finished loading,
// autofocus on the username field
$('input#id_username').focus();
});
</script>
{% endblock %}
If you're not already using Jquery you will need to include a link to it in the page too (something like <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>).

Related

How to resolve "jinja2.exceptions.UndefinedError: 'nutrition' is undefined" error in Flask for CS50 Final Project

I am getting following error when i run the flask: jinja2.exceptions.UndefinedError: 'nutrition' is undefined. I tried several things but still couldn't resolve it.
Please help resolve the problem.
Code is below:
#app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
nutrition = Recipe_nutrition(request.form.get("recipes"))
instructions = Instructions(request.form.get("recipes"))
return render_template("index.html", nutrition = nutrition, instructions = instructions)
# User reached route via GET (as by clicking a link or via redi)
else:
return render_template("index.html")
{% extends "layout.html" %}
{% block title %}
Index
{% endblock %}
{% block main %}
<form action="/" method="post">
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="recipes" placeholder="Recipe" type="text" required/>
</div>
<button class="btn btn-primary" type="submit">Search</button>
</form>
<table class="table table-striped" style="width:100%">
<tr>
<th>Nutrition</th>
<th>Amount</th>
<th>Units</th>
</tr>
{% for keys, values in nutrition.items() %}
<tr>
<td>{{ keys }}</td>
<td>{{ values[0] }}</td>
<td>{{ values[1] }}</td>
</tr>
{% endfor %}
</table>
<table class="table table-striped" style="width:100%">
<tr>
<th>#</th>
<th>Steps</th>
</tr>
{% for keys, values in instructions.items() %}
<tr>
<td>{{ keys }}</td>
<td>{{ values }}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
In your Jinja template, you both access nutrition and instructions, but you only set them in case of a POST request.
You have several options now.
Either set both to an empty list, and also pass them into your render_template function for the GET case (your elsebranch).
Or return a different template, where nutrition and instructions are not necessary.
Maybe there is also a builtin Jinja solution, but I do not know one.

Django Display a selection list

I am trying to implement a form where candidates can be selected for approval processing. I want to display a list of candidates, so their data can be viewed during selection.
models.py
class SubmissionApproval(models.Model):
candidate=models.ForeignKey(Candidate,on_delete=models.CASCADE)
clientProcess=models.ForeignKey(ClientProcessDetails,verbose_name="Client
Process",help_text="Process",on_delete=models.PROTECT)
dateSubmitted=models.DateTimeField(auto_now_add=True)
comments=models.CharField("Comments",max_length=200,blank=True,null=True)
class Meta:
verbose_name="First Stage Approval"
unique_together=(('candidate','clientProcess'),)
def __str__(self):
return self.candidate.name
views.py
def submissionApprovalList(request):
object_list=Candidate.objects.all()
if request.method=="POST":
fm=SubmissionApprovalFormList(request.POST)
print("Reached Post")
if fm.is_valid():
print("Printing Candidates Start")
for item in fm.cleaned_data['candidates']:
print(item)
print("Printing candidates End")
else:
fm=SubmissionApprovalFormList()
return render(request,'itrecruitment/firstStageSubmissionList.html',{'form':fm,'object_list':object_list })
forms.py
class SubmissionApprovalFormList(forms.Form):
candidates=forms.ModelMultipleChoiceField(
queryset=Candidate.objects.all(), widget=forms.CheckboxSelectMultiple
)
template
{% extends "seekgeek/base.html" %}
{% block content %}
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<h3 class="box-title">Select Candidates for First Stage Submission</h3>
<button type="button" class="btn btn-primary pull-right">Add Candidate </button>
</div>
<!-- /. box-header -->
<div class="box-body table-responsive">
<!-- form details -->
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
{% bootstrap_messages %}
<form method="post" enctype="multipart/form-data" >
{% csrf_token %}
<table class="table table-bordered table-hover datatable2">
<thead>
<tr>
<td><b>Select</b></td>
<td><b>Candidate No</b></td>
<td><b>Candidate Name</b></td>
<td><b>Current CTC (LPA)</b></td>
<td><b>Expected CTC (LPA)</b></td>
<td><b>Experience in Yrs</b></td>
<td><b>Recruiter</b></td>
<td><b>Latest Status</b></td>
<td><b>Languages</b></td>
<td><b>Updated</b></td>
</tr>
</thead>
<!-- ./ table head -->
<tbody>
{% for obj in object_list %}
<tr>
<!--Select field for Form -->
<td> {{ form.candidates.0 }} </td>
<!--Select field for Form -->
<td>{{ obj.id }}</td>
<td>{{ obj.name }}</td>
<td>{{ obj.currentCTC }}</td>
<td>{{ obj.expectedCTC }}</td>
<td>{{ obj.experience }}</td>
<td>{{ obj.recruiter }}</td>
<td>{% if obj.latestRecStatus %}
<p><a class='text-green' href="{{ obj.latestRecStatus.get_absolute_url }}">{{ obj.latestRecStatus }}</a></p>
<p><a class='text-yellow' href="{% url 'clients:process-detail' obj.latestRecStatus.clientProcess.id %}"> {{ obj.latestRecStatus.clientProcess }} </a></p>
{% else %}
<p>No Status</p>
{% endif %}
</td>
<td>
{% for item in obj.programmingLanguages.all %}
<p>{{ item }}</p>
{% endfor %}
</td>
<td>{{ obj.updated }}</td>
</tr>
{% endfor %}
</tbody>
<!-- /. table body -->
</table>
<!-- /. table -->
{% buttons %}
<button type="submit" class="btn btn-primary">
Submit
</button>
{% endbuttons %}
</div>
<!-- /. box body -->
</div>
<!-- /. box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
{% endblock %}
What is the correct way of doing this. intention is similar to change list form in django admin

Toggle Checkbox in Django and Write to Database

I have some model
from django.db import models
class Model1(models.Model):
title = models.CharField(max_length=300)
boolean1 = models.BooleanField(default=False)
boolean2 = models.BooleanField(default=False)
and am currently displaying all database entries in a template via the following bootstrap table:
<div class = 'table-responsive'>
<table class='table table-striped'>
<thead>
<th>Title</th>
<th>Boolean 1</th>
<th>Boolean 2</th>
</thead>
{% if model1_list %}
{% for Model1 in model1_list %}
<tbody>
<tr>
<td>{{ Model1.title }}</td>
<td>{{ Model1.boolean1 }}</td>
<td>{{ Model1.boolean2 }}</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
</div>
I'd like to display the boolean values as checkboxes rather than text, and to be able to check and uncheck the values and have it be reflected in the database (i.e., if the database is checked, the value should be True).
What would be a way to implement this?
Just use IF's:
<div class = 'table-responsive'>
<table class='table table-striped'>
<thead>
<th>Title</th>
<th>Boolean 1</th>
<th>Boolean 2</th>
</thead>
{% if model1_list %}
{% for Model1 in model1_list %}
<tbody>
<tr>
<td>{{ Model1.title }}</td>
<td>
<div class="checkbox">
<label><input type="checkbox" {% if Model1.boolean1 %} checked {% endif %}>Boolean 1</label>
</div>
</td>
<td>
<div class="checkbox">
<label><input type="checkbox" {% if Model1.boolean2 %} checked {% endif %}>Boolean 2</label>
</div>
</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
</div>
When the user clicks, you want to send this information to the DB without refreshing the page? If yes, you need to do an ajax request to set this information to DB using JSON.Something like that:
$.ajaxFunction = function(){
var boolean1 = $("#boolean1").val(),
boolean2 = $("#boolean2").val(),
csrf_token = $("#csrf_token").val();
data_send = {
"boolean1": boolean1,
"boolean2": boolean2,
"csrfmiddlewaretoken": csrf_token
};
//jquery
$.ajax({
type: "post",
url: $("/url/ajax/").val(),
data: data_send,
success: function(data_receive){
if(data['boolean1']==true){
...
}
...
}
});
}
If no, you can just do a to POST this information and refresh the page!

Django only loads base.html

I'm trying to learn Django and am trying to setup a user login system. My site only shows the base.html contents, and not the contents of login.html. If I remove the extends base.html, the login form seems to show up correctly. Am I doing something wrong?
login.html
{% extends "base.html" %}
{% load url from future %}
{% block content %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action="{% url 'django.contrib.auth.views.login' %}">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
{% endblock %}
base.html
<body>
<div>
{{ user }}
{% if user.is_anonymous %}
login
{% else %}
logout
{% endif %}
</div>
Your base.html template is missing a corresponding {% block content %}{% endblock content %} and also a closing </body> tag. There's nowhere for the content in login.html to go.
Brandon is right.
you can think {%block content %} as a hole in your base.html and the extended file only replace/fill in that hole.

login Page by using django forms

I am New beginner in python and django...
i want to know how can i create a login form by using django forms(forms.py)
In your urls.py file link to the built in Django login view, and pass in the path to a template you wish to use as the login page:
(r'^login/$', 'django.contrib.auth.views.login', {
'template_name': 'myapp/login.html'
}),
And here is an example of what the template my look like (from the Django docs):
{% extends "mybase.html" %}
{% block content %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action="{% url 'django.contrib.auth.views.login' %}">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
{% endblock %}
Yes, you can. Actually, you don't need to create your own form. Simply use auth module and create your own login template. Read this: http://docs.djangoproject.com/en/dev/topics/auth/