django-bootstrap5 and button alignment - django

I want to display a button next to a form instead of below:
This is how it looks:
should look like this:
corresponding code:
form:
class TheForm(forms.Form):
var = forms.ChoiceField(choices = choices, label = "")
temp
late:
{% if TheForm %}
<form method = "post">
{% csrf_token %}
{% bootstrap_form TheForm %}
{% bootstrap_button button_type="submit" content="OK" %}
</form>
{% endif %}
EDIT:
Got it working, but the code only works with one input field:
I imagined it would look like this:
but the produced code looks weird too:
<form method="POST" action="/singleDevice">
<input type="hidden" name="csrfmiddlewaretoken" value="...">
<div class="row">
<div class="col-9">
<div class="col-12">
<select name="env" class="form-select" id="id_env">
<option value="0">A</option>
<option value="3">NB</option>
</select>
</div>
<div class="col-12">
<label class="visually-hidden" for="id_Number">directly enter a number</label>
<input type="text" name="Number" class="form-control" placeholder="directly enter a number" id="id_Number">
</div>
</div>
<div class="col-3">
<button class="btn btn-primary" type="submit">OK</button>
</div>
</div>
</form>

Try bootstrap Grid system,
template.html
{% if TheForm %}
<form method = "post">
{% csrf_token %}
<div class="row"> <!-- creates a row of 12 parts -->
<div class="col-lg-9"> <!-- Creates a column with width of 9 parts out of the above 12 parts -->
{% bootstrap_form TheForm %}
</div>
<div class="col-lg-3"> <!-- Creates a column with width of remaining 3 parts out of the above 12 parts -->
{% bootstrap_button button_type="submit" content="OK" %}
</div>
</div>
</form>
{% endif %}
EDIT: CSS TO SET BUTTON AT THE END OF FORM
<form method="POST" action="/singleDevice">
<input type="hidden" name="csrfmiddlewaretoken" value="...">
<div class="row">
<div class="col-9">
<div class="col-12">
<select name="env" class="form-select" id="id_env">
<option value="0">PROD</option>
<option value="1">QA</option>
<option value="2">DEV</option>
<option value="3">NB</option>
</select>
</div>
<div class="col-12">
<label class="visually-hidden" for="id_Number">directly enter a number</label>
<input type="text" name="Number" class="form-control" placeholder="directly enter a number" id="id_Number">
</div>
</div>
<div class="col-3">
<button class="btn btn-primary form-submit-button" type="submit">OK</button>
</div>
</div>
</form>
base.css:
.form-submit-button{
display: inline-block;
margin-top: 95%; /* (approx) */
}
CHANGES: I have set a classname to the submit button and pushed the submit button to the bottom end of the y-axis using margin-top (percentage ensures that it stays below even on resizing)

Related

MultiValueDictKeyError at upload/

Good day people, a part of my project has a form action that takes user input and saves it in the database. the user has an option to either select the category from the select field or enter a new category if the category does not exit in the select field but I get "MultiValueDictKeyError at upload/"
below is the template and the corresponding view to the form action:
upload.html
{%extends 'base.html'%}
{%block content%}
<div class="container" id="containers">
<div class="row" style="width: 40%;">
<form action="upload" method="post" enctype="multipart/form-data">
{% csrf_token %}
<ul class="collection">
<li class="collection-item">
<div class="input-field" >
<input placeholder="Enter the product name here..." id="first_name" type="text" class="validate" name="product_name">
<label for="first_name">Product name</label>
</div>
</li>
<li class="collection-item">
<div class="input-field" >
<select class="browser-default" name="the_category">
<option value="" disabled selected>Category</option>
{% for category in categories %}
<option value="{{category.name}}">{{category.name}}</option>
{% endfor%}
</select>
</div>
</li>
<li class="collection-item">
<div class="input-field" style="margin: 5px;">
<input name="new_category" placeholder="Type here..." id="first_name" type="text" class="validate">
<label for="first_name">New Category</label>
</div>
</li>
<li class="collection-item"><div class="input-field " >
<input placeholder="Enter the price"id="username" type="number" class="validate" name="prize">
<label for="password">Price</label>
</div>
</li>
<li class="collection-item">
<div class="input-field">
<input name="locate" placeholder="Enter the location" id="first_name" type="text" class="validate">
<label for="first_name">Location</label>
</div>
</li>
<li class="collection-item">
<div class="input-field" >
<textarea id="textarea1" class="materialize-textarea" name="describe"></textarea>
<label for="textarea1">Descriptiion</label>
</div>
</li>
<li class="collection-item">
<div class="file-field input-field">
<div class="btn">
<span>File</span>
<input type="file" name="image">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text">
</div>
</div>
</ul>
<button class="btn waves-effect waves-light right" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</form>
</div>
</div>
{%endblock content%}
views.py (for upload)
def upload(request):
categories=Category.objects.all()
if request.method=='POST':
images=request.FILES.get('image')
data=request.POST
location,created=LOCATION.objects.get_or_create(Location=data['locate'])
if data['the_category']!='none':
category=Category.objects.get(name=data['the_category'])
elif data['new_category']!='':
category=Category.objects.create(name=data['new_category'])
else:
category=None
models.Product.objects.create(
name=data['product_name'],
image=images,
category=category,
description=data.get('describe'),
Location=location,
price=data.get('prizes'),
created=datetime.datetime.now(),
is_available=True
)
return render(request,'upload.html',{'categories':categories})

I am always getting none from request.POST.get in django

nam and mob field are userinput fields which i am using for user input and later i am using them for filtering
{% block content %}
<form class="form-signin" action="" method="POST">
{% csrf_token %}
<div class="mb-3">
<input type="text" name="nam" id="nam" class="form-control-sm center-block" placeholder="Nam" autofocus>
</div>
</div>
<div class="mb-3">
<select class="custom-select center-block" name="mob" id="mob" >
<option>{{ customer.sponsor }}</option>
{% for i in sponsor %}
<option value="{{ i.mobile }}"> {{ i.mobile|add:' - '|add:i.name }} </option>
{% endfor %}
</select>
<div class="invalid-feedback">
Please select a valid Existing Customer.
</div>
</div>
<div class="mb-3">
Search
Urls.py
path('customer_view',views.customer_view,name='customer_view')
Views.py
def customer_view(request):
print(request.method )
name1 = str(request.POST.get('nam'))
print(name1)
mobile1 = str(request.POST.get('mob'))
print(mobile1)
customers_list = customer.objects.filter(
mobile=mobile1) & customer.objects.filter(name=name1)
sponsors = customer.objects.all().distinct('mobile')
ctx = { 'customer': customers_list, 'sponsor': sponsors }
return render(request, 'pages/customer_view.html', ctx)
You use href which does not submit the form. You need a submit button and change your action of your form to your view url. Try this:
{% block content %}
<form class="form-signin" action="{% url 'customer_view' %}" method="POST">
{% csrf_token %}
<div class="mb-3">
<input type="text" name="nam" id="nam" class="form-control-sm center-block" placeholder="Nam" autofocus>
</div>
</div>
<div class="mb-3">
<select class="custom-select center-block" name="mob" id="mob" >
<option>{{ customer.sponsor }}</option>
{% for i in sponsor %}
<option value="{{ i.mobile }}"> {{ i.mobile|add:' - '|add:i.name }} </option>
{% endfor %}
</select>
<div class="invalid-feedback">
Please select a valid Existing Customer.
</div>
</div>
<div class="mb-3">
<input type="submit" value="Search"/>
.
.
...
In your form, you write a button as:
Search
But this thus means that this is just a link that links to a new page. As a result, the browser will make an (empty) GET request to the given url, and never submit the form.
You can construct a button that submits the form with:
<form class="form-signin" action="{% url 'customer_view' %}" method="post">
<!-- … -->
<button type="submit" class="btn btn-primary btn-sm" role="button">Search</button>
<!-- … -->
</form>
That being said, a search is often done with a GET request, so you might want to change method="get", and obtain the parameters through request.GET.get(..) instead.

Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['employees\\/edit\\/(?P<pk>[0-9]+)\\/$']

Building an Employee application, After updating an Employee using a form, it just shows this error and the Url seems correct so I can really say where the error is coming from
I've crosschecked all my url patterns my views and my url in the form and also tried using the solution in this question, this gives me a bigger error
urls.py
urlpatterns = [
path('edit/<int:pk>/', views.edit, name = 'edit'),
]
views.py
#login_required(login_url='/accounts/login')
def edit(request, pk):
employ = get_object_or_404(Employee, id=pk)
logging.info(type(employ))
departments = Department.objects.all()
context = {
'employ': employ,
'departments':departments
}
if request.method == "POST":
first_name = request.POST['first_name']
last_name = request.POST['last_name']
name = last_name +' '+first_name
employee_id = request.POST['employee_id']
email = request.POST['email']
department = Department.objects.get(dept_name = request.POST['department'])
address = request.POST['address']
employment_type = request.POST['employment_type']
employment_status = request.POST['employment_status']
role = request.POST['role']
marital_status = request.POST['marital_status']
gender = request.POST['gender']
join_date = request.POST['join_date']
end_date = None if len(request.POST['end_date']) ==0 else request.POST['end_date']
location = request.POST['location']
credentials = request.POST['credentials']
passport = request.POST['passport']
hod = request.POST['hod']
phone_number = request.POST['phone_number']
date_of_birth = request.POST['date_of_birth']
date_added = datetime.now()
if Employee.objects.filter(employee_id = employee_id).exists() or Employee.objects.filter(email = email).exists():
messages.error(request, 'That ID/Email is Taken')
return redirect('edit')
else:
employee = Employee(first_name='first_name',last_name='last_name',email='email',
employee_id='employee_id',department='department',address='address',employment_type='employment_type',
employment_status='employment_status',role='role',marital_status='marital_status',gender='gender',join_date='join_date',
end_date='end_date',location='location',credentials='credentials',passport='passport',hod='hod',
phone_number='phone_number',date_added='date_added',date_of_birth='date_of_birth')
employee.save()
messages.success(request, 'Employee Created')
return redirect('all')
return render(request, 'employees/edit.html', context, employ)
edit.html
<form method = 'POST' action="{% url 'edit' pk=employ.pk %}" class="m-b-30" enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for='first_name' class="control-label">First Name <span class="text-danger">*</span></label>
<input name='first_name' class="form-control" type="text" required value="{{employ.first_name}}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='last_name' class="control-label">Last Name</label>
<input name='last_name' class="form-control" type="text" required value="{{employ.last_name }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='employee_id' class="control-label">Employee ID <span class="text-danger">*</span></label>
<input name='employee_id' class="form-control" type="number" required value="{{employ.employee_id }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='email' class="control-label">Email <span class="text-danger">*</span></label>
<input name='email' class="form-control" type="email" required value="{{employ.email }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='phone_number' class="control-label">Phone Number</label>
<input name='phone_number' class="form-control" type="text" required value="{{employ.phone_number }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='gender' class="control-label">Gender</label>
<select name = 'gender' class="form-control" value = "{{employ.gender}} " type="text" >
<option>select gender</option>
{% if employ.gender == 'Male' %}
<option selected ='selected'>Male</option>
{% else %}
<option selected ='selected'>Female</option>
{% endif %}
<option>Male</option>
<option>Female</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='marital_status' class="control-label">Marital Status</label>
<select name='marital_status' class="form-control" value = "{{employ.marital_status}} " type="text" >
{% if employ.marital_status == 'Married' %}
<option selected ='selected'>Married</option>
{% else %}
<option selected ='selected'>Single</option>
{% endif %}
<option>select martial status</option>
<option>Married</option>
<option>Single</option>
<option>Single</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='date_of_birth' class="control-label">Date of Birth <span class="text-danger">*</span></label>
<input name='date_of_birth' class="form-control" type="date" required value="{{employ.date_of_birth|date:'Y-m-d' }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='address' class="control-label">Address </label>
<input name='address' class="form-control" type="text" required value="{{employ.address }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='department' class="control-label">Department <span class="text-danger">*</span></label>
<select name = 'department' type="text" class="form-control" value = "{{employ.department}} " >
<option>select department</option>
{% for department in departments %}
{% if employ.department == department %}
<option selected ='selected'>{{employ.department}}</option>
{% endif %}
<option>{{department.dept_name}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='employment_type' class="control-label">Employment Type </label>
<select id= "employment_type" name='employment_type' type="text" class="form-control" value = "{{employ.employment_type}} " >
{% if employ.employment_type == 'Contract' %}
<option selected ='selected'>Contract</option>
{% elif employ.employment_type == 'Fulltime' %}
<option selected ='selected'>Fulltime</option>
{% else %}
<option selected ='selected'>Intern</option>
{% endif %}
<option>select employment type</option>
<option>Contract</option>
<option>Fulltime</option>
<option>Intern</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='join_date' class="control-label">Join Date <span class="text-danger">*</span></label>
<input name='join_date' class="form-control " type="date" required value="{{employ.join_date|date:'Y-m-d' }}">
</div>
</div>
<div class="col-sm-6" id="end_date">
<div class="form-group">
<label for='end_date' class="control-label">End Date <span class="text-danger">*</span></label>
<input name='end_date' class="form-control " type="date" value="{{employ.end_date|date:'Y-m-d' }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='employment_status' class="control-label">Employment Status </label>
<select name='employment_status' type="text" class="form-control" value="{{employ.employment_status}}" >
{% if employ.employment_status == 'Active' %}
<option selected ='selected'>Active</option>
{% else %}
<option selected ='selected'>Inactive</option>
{% endif %}
<option>select employment status</option>
<option>Active</option>
<option>Inactive</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='role' class="control-label">Role </label>
<input name='role' class="form-control" type="text" required value="{{employ.role }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='location' class="control-label">Work Location </label>
<input name='location' class="form-control" type="text" required value="{{employ.location }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='hod' class="control-label">HOD </label>
<select name='hod' class="form-control" type="text" >
<option>Select HOD</option>
{% for department in departments %}
{% if employ.department.lead == department.lead %}
<option selected ='selected'>{{employ.department.lead}}</option>
{% endif %}
<option>{{department.lead}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='passport' class="control-label">Upload passport </label>
<input name='passport' type="file" accept="image/*" value="{{employ.passport }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for='credentials' class="control-label">Add Credentials </label>
<input name='credentials' type="file" accept="image/*" value="{{employ.credentials }}">
</div>
</div>
</div>
<div class="m-t-20 text-center">
<button class="btn btn-primary">Update Employee</button>
</div>
</form>
it's meant to be submitted and routed to edit.hmtl in case there's any error while submitting
When you redirect to the edit view, you need to pass the primary key.
return redirect('edit', pk=employ.pk)
As an aside, it's not recommended to access values from request.POST directly. Have a look at Django forms.

Django: Redirect Change Password URL

I have the following two URLs:
url(r'^change-password/$',django.contrib.auth.views.password_change,{'template_name': 'meta/changepassword.html', 'post_change_redirect': '/password-changed/'},name='change_password'),
url(r'^change-passwordiOS/$',django.contrib.auth.views.password_change,{'template_name': 'meta/changepassword.html', 'post_change_redirect': '/password-changed/'},name='change_passwordiOS'),
I thought if I used the following within the change password form it would override what URL would be loaded:
{% if 'iOS' in request.path %}
<input type="hidden" name="next" value="/profileiOS/" />
{% endif %}
But when I reach the change password from the url(r'^change-passwordiOS/$' and click the "Change Button" it does not goto the /profileiOS/ as expected but the standard /profile/ URL.
Any help would be appreciated.
/change-password/ view:
#login_required
def password_changed(request):
messages.success(request, 'Your password has been changed.')
return redirect(reverse('profile'))
Full Change Password Form:
<form class="form-horizontal" role="form" method="post" action="">
{% csrf_token %}
<fieldset>
<div class="form-group">
<label class="col-md-6 control-label">{{ form.old_password.label }}:</label>
<div class="col-md-6">
<input name="old_password" type="password" class="form-control"/>
<div class="text-danger">
{% for error in form.old_password.errors %}{{ error }}<br/>{% endfor %}
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-6 control-label">{{ form.new_password1.label }}:</label>
<div class="col-md-6">
<input name="new_password1" type="password" class="form-control"/>
<div class="text-danger">
{% for error in form.new_password1.errors %}{{ error }}<br/>{% endfor %}
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-6 control-label">{{ form.new_password2.label }}:</label>
<div class="col-md-6">
<input name="new_password2" type="password" class="form-control"/>
<div class="text-danger">
{% for error in form.new_password2.errors %}{{ error }}<br/>{% endfor %}
</div>
</div>
</div>
<div class="form-group">
<div class="text-right col-sm-12">
<button type="submit" class="btn btn-primary">Change Password^</button>
</div>
</div>
</fieldset>
{% if 'iOS' in request.path %}
<input type="hidden" name="next" value="/profileiOS/" />
{% endif %}
</form>
You are manually redirecting to /profile/ in password_changed view. You can change your redirect logic to depend on post param from template:
#login_required
def password_changed(request):
messages.success(request, 'Your password has been changed.')
return redirect(request.POST.get('next', reverse('profile')))

Django template for loop inside <select> renders values after the select

I'm trying to use JQuery widget Multiple select instead of default.
As you can see, I'm trying to render select options right into <select> tag but, it's weird that it is being rendered after </select> tag. (for loop is inside this tag, not after)
EDIT:
Simly, this is in the template:
<tag> {% for choice in field.choices %}{{ choice }}{%endfor%} </tag>
but Django renders it like it was:
<tag></tag> {% for choice in field.choices %}{{ choice }} {%endfor%}
This is rendered:
<div class="col-xs-5">
<select name="from[]" id="multiselect" class="form-control" size="8" multiple="multiple">
</select> # options are render after this tag
<option value="97">Slovak</option>
<option value="98">Russian</option>
<option value="99">Magyar</option>
<option value="100">English</option>
<option value="101">Croatian</option>
<option value="102">Spanish</option>
<option value="103">Dutch</option>
<option value="104">Estonian</option>
<option value="105">French</option>
<option value="106">DSADSA</option> etc....
This is the template:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% load static %}
{% block head %}
<script type="text/javascript" src="{% static "js/scripts/multiselect.min.js" %}"></script>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$('#multiselect').multiselect();
});
</script>
{% endblock %}
{% block content %}
<h1>Become a translator</h1>
<form id="user_form" method="post" action="">
{% csrf_token %}
{{ register_as_translator_form | crispy }}
<button class="accordion" type="submit" name="submit" value="Register">Register</button>
</form>
<div class="row">
<div class="col-xs-5">
<select name="from[]" id="multiselect" class="form-control" size="8" multiple="multiple">
{% for choice in register_as_translator_form.languages %}
{{ choice }}
{% endfor %}
</select>
</div>
<div class="col-xs-2">
<button type="button" id="multiselect_rightAll" class="btn btn-block"><i
class="glyphicon glyphicon-forward"></i></button>
<button type="button" id="multiselect_rightSelected" class="btn btn-block"><i
class="glyphicon glyphicon-chevron-right"></i></button>
<button type="button" id="multiselect_leftSelected" class="btn btn-block"><i
class="glyphicon glyphicon-chevron-left"></i></button>
<button type="button" id="multiselect_leftAll" class="btn btn-block"><i
class="glyphicon glyphicon-backward"></i></button>
</div>
<div class="col-xs-5">
<select name="to[]" id="multiselect_to" class="form-control" size="8" multiple="multiple"></select>
</div>
</div>
{% endblock %}
Unfortunately, it renders this:
Do you know what to do?
That could happen if register_as_translator_form.languages return string list, try this way:
<select name="from[]" id="multiselect" class="form-control" size="8" multiple="multiple">
{% for choice in register_as_translator_form.languages %}
<option value="{{ choice }}">{{ choice }}</option>
{% endfor %}
</select>