I have a form that contains two select inputs one is for categories and the other for sub categories the form should work like this user should choose an option in the categories and based on that option the sub category options should be updated with new values. but for some reason the sub category options aren't updating
template dashboard.html
{% block body %}
<form>
{% csrf_token %}
<div class="row">
<div class="input-field col s6 offset-s3">
<select id="list">
<option value="" disabled selected>Choose your Category</option>
<option value="education">University/College</option>
<option value="hospital">Hospital</option>
<option value="business">Business Organizations</option>
</select>
<label>Categories</label>
</div>
<div class="input-field col s6 offset-s3">
<select>
<option value="" disabled selected>Choose your Category</option>
{% for d in data %}
<option value="">{{ d.username }}</option>
{% endfor %}
</select>
<label>Sub Categories</label>
</div>
</div>
</form>
{% endblock %}
{% block script %}
<script type="text/javascript">
$('#list').change(function() {
$.ajax({
type: 'POST',
url: '/dashboard/',
data: {
category: $('#list').val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
}
});
});
</script>
{% endblock %}
view.py
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
def dashboard(request):
if not request.user.is_authenticated:
return redirect('index')
else:
if request.method == 'POST':
category = request.POST['category']
#Here i am using User table because category table is empty
data = User.objects.all()
print(data)
return render(request, 'usecases/dashboard.html', {'data': data})
else:
return render(request, 'usecases/dashboard.html')
This is your subcategories where I just add an id #sub_categories
<select id='sub_categories'>
<option value="" disabled selected>Choose your Category</option>
{% for d in data %}
<option value="">{{ d.username }}</option>
{% endfor %}
</select>
<label>Sub Categories</label>
JS
$.ajax({
type: 'POST',
url: '/dashboard/',
data: {
category: $('#list').val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success:function(response){
$('#sub_categories').replaceWith($("#sub_categories",response))
}
});
Related
Currently I am trying to show/hide an inline element on the page when a specific variant of the product is selected in a <select> input. I've tried multiple tries with jquery to access the select with no luck and even tried inline <% if %> liquid tag. Any help would be greatly appreciated!
Basically I want a textbox to show when two of the options are selected else not show the textbox.
Below is what I have:
{% if product.variants.size > 1 %}
<div id="product-variants" class="card_options">
<select id="product-select-{{ product.id }}" name="id" class="hidden line-item-property__field">
{% for variant in product.variants %}
<option {% if variant == product.selected_or_first_available_variant %} selected="selected" {% endif %} value="{{ variant.id }}" data-sku="{{ variant.sku }}">{{ variant.title }} - {{ variant.price | money }}</option>
{% endfor %}
</select>
</div>
<input type="hidden" name="id" value="{{ product.selected_or_first_available_variant.id }}" />
{% endif %}
Now if only I could add something like below to add the textbox when option1 or option2 are selected.
<-- Same as above -->
{% if product.variants.size > 1 %}
<div id="product-variants" class="card_options">
<select id="product-select-{{ product.id }}" name="id" class="hidden line-item-property__field">
{% for variant in product.variants %}
<option {% if variant == product.selected_or_first_available_variant %} selected="selected" {% endif %} value="{{ variant.id }}" data-sku="{{ variant.sku }}">{{ variant.title }} - {{ variant.price | money }}</option>
{% endfor %}
</select>
</div>
<input type="hidden" name="id" value="{{ product.selected_or_first_available_variant.id }}" />
{% endif %}
<-- End Same as above -->
<-- New Code -->
{% if variant != option1 %}
<p class="line-item-property__field" id=card_message>
<label for="card-message">Card Message:</label>
<span id="char-counter"></span><span id="message-alert"></span>
<textarea id="message-textarea" maxlength="250" name="properties[Card Message]"></textarea>
</p>
{% else %}
<span id="placeholder"></span>
{% endif %}
This is what it should look like:
UPDATE: Apparently my solution with jQuery worked. I was just targeting the wrong select on the page. I had to retrieve the select dynamically instead of finding it by class or id. For some reason Shopify creates a second <select> input and hides the one you see in products.liquid document. So I had to resort to using $(".selector-wrapper select").bind('change', function(event) {//do something} and var selected = $('.selector-wrapper select option:selected').val(); to retrieve the values of the options. I'll link a fiddle I created with the same logic, you will just have to update it with what I listed above. Hope this helps anyone looking for same solution.
Fiddle Demo
I have the following HTML template in Django to POST a request when the user selects the select option. The console shows the correct value based on what the user selects. My problem is when I push the submit button my POST gets posted as None on the submitted view. How can I get it to post on button click, i've aliased the button as my_select.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form action = "{% url 'submitted' %}" form method = "POST">
{% csrf_token %}
<h2>Applications:</h3></br>
{% for app in retreivecheckbox %}
<li><input type="checkbox" name="report_id" value ="{{app.report_id}}" checked> {{ app }}
</li>
{% endfor %}
</div>
</div>
<div class="row">
<div class="col">
<label for="accesslevel"><h3>Access Level</h3></label>
<select title ="accesslevelid" class="form-control my_select" id="accesslevelid">
<option value=""> Please select your access level </option>
<option value="7"> Facility </option>
<option value="5"> Division </option>
<option value = "3"> Corporate </option>
<option value = "6"> Market </option>
<option value = "4"> Group </option>
</select>
</div>
<div class="col">
<label for="phi"><h3>PHI</h3></label>
<select class="form-control my_select" id="phi" title = "phi" >
<option value = ""> Please select if you need access to PHI data </option>
<option value = "0"> No </option>
<option value = "1"> Yes </option>
</select>
</div>
</div>
<div class="row">
<div class="container">
<div class="row">
<div class="col">
</br> </br>
<button href="{% url 'submitted' %}" class="btn btn-primary my_select" type = "submit"> Submit </button>
<script>
$(document).ready(function () {
$('.my_select').on('click', function () {
var phi = $('#phi').val();
var accesslevelid = $('#accesslevelid ').val();
$.ajax({ url: "{% url 'submitted' %}",
headers: { 'X-CSRFToken': '{{ csrf_token }}' },
data: {
phi: phi,
accesslevelid: accesslevelid,
},
type: 'POST',
success: function (result) {
;
},
});
});
});
</script>
</div>
</form>
Change your button and javascript to this:
<button class="btn btn-primary my_select" type="submit">Submit</button>
<script>
$(document).ready(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var phi = $('#phi').val();
var accesslevelid = $('#accesslevelid').val();
$.ajax({
url: "{% url 'submitted' %}",
headers: { 'X-CSRFToken': '{{ csrf_token }}' },
data: {
phi: phi,
accesslevelid: accesslevelid,
},
type: 'POST',
success: function (result) {
// do something with result
},
});
});
});
</script>
this is what i would normally use if you use Jquery 3.2.1
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
method: "POST",
data: $(this).serialize()
}).done(function(xhr) {
// do something
});
});
also update your select elements to have
<select class="form-control my_select" id="phi" name="phi">
rather than
<select class="form-control my_select" id="phi" title = "phi" >
notice i have changed the "title" attr to "name"
I have my requestaccess view below, which will write to my database if I remove the if request.method == 'POST', but if i keep it in. The request is never written. I'm trying to understand why the POST isn't occurring and how to make it happen?
def requestaccess(request):
owner = User.objects.get (formattedusername=request.user.formattedusername)
reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername, active = 1).values('report_name_sc')
reportIds = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_id', flat=True)
checkedlist = request.GET.getlist('report_id')
reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True)
coid = User.objects.filter(coid = request.user.coid).filter(formattedusername=request.user.formattedusername)
facilitycfo = QvDatareducecfo.objects.filter(dr_code__exact = coid , active = 1, cfo_type = 1).values_list('cfo_ntname', flat = True)
divisioncfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 2).values_list('cfo_ntname', flat = True)
selectedaccesslevel = '7'
if request.method == 'POST':
selectedaccesslevel = request.POST.get('accesslevelid')
print(selectedaccesslevel)
selectedphi = '0'
if request.method == 'POST':
selectedphi = request.POST.get('phi')
print(selectedphi)
if request.method == 'POST':
for i in checkedlist:
requestsave = QVFormAccessRequest(ntname = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid, facility = owner.facility, title = owner.title
,report_id = i, accesslevel_id = selectedaccesslevel, phi = selectedphi, access_beg_date = '2017-01-01 00:00:00', access_end_date = '2017-01-31 00:00:00')
requestsave.save()
args = {'retreivecheckbox': reportlist, 'cfo7':facilitycfo, 'cfo5':divisioncfo, 'checkedlist':checkedlist }
return render(request,'accounts/requestaccess.html', args)
# return render(request, 'accounts/requestaccess.html', args)
My request.method == 'POST' statements never return the correct value only the hard coded one for a test.
My template requestaccess.html can be found below. I can see the POST request for the ajax function being updated as i change the select options and when I click on the button.
{% extends 'base.html' %}
{% block head %}
<title> Access Request Form </title>
{% endblock %}
{% block body %}
<div class="container">
<div class="row">
<div class="col">
<h2>{{ user.username }}</h2></br>
<ul>
<li>Employee First Name: {{ user.first_name }}</li>
<li>Employee Last Name: {{ user.last_name }}</li>
<li>Coid: {{ user.coid }}</li>
<li>Facility: {{ user.facility }}</li>
<li>Title: {{user.title}}</li>
</ul>
</div>
<div class="col">
<form action = "{% url 'requestaccess' %}" form method = "POST">
{% csrf_token %}
<h2>Applications:</h3></br>
{% for app in retreivecheckbox %}
<li><input type="checkbox" name="report_id" value ="{{app.report_id}}" checked> {{ app }}
</li>
{% endfor %}
</div>
</div>
<div class="row">
<div class="col">
<label for="accesslevel"><h3>Access Level</h3></label>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select title ="accesslevelid" class="form-control my_select" id="accesslevelid">
<option value=""> Please select your access level </option>
<option value="7"> Facility </option>
<option value="5"> Division </option>
<option value = "3"> Corporate </option>
<option value = "6"> Market </option>
<option value = "4"> Group </option>
</select>
</div>
<div class="col">
<label for="phi"><h3>PHI</h3></label>
<select class="form-control my_select" id="phi" title = "phi" >
<option value = ""> Please select if you need access to PHI data </option>
<option value = "0"> No </option>
<option value = "1"> Yes </option>
</select>
</div>
</div>
<div class="row">
<div class="container">
<div class="row">
<div class="col">
</br> </br>
<button href="{% url 'submitted' %}" class="btn btn-primary my_select" type = "submit"> Submit </button>
<script>
$(document).ready(function () {
$('.my_select').on('change', function () {
var phi = $('#phi').val();
var accesslevelid = $('#accesslevelid ').val();
$.ajax({ url: "{% url 'requestaccess' %}",
headers: { 'X-CSRFToken': '{{ csrf_token }}' },
data: {
phi: phi,
accesslevelid: accesslevelid,
},
type: 'POST',
success: function (result) {
;
},
});
});
});
</script>
</div>
</form>
{% endblock %}
Below is the console which shows the POST:
[07/Dec/2017 13:21:14] "GET /account/requestaccess/?report_id=84&report_id=87&report_id=88 HTTP/1.
3
[07/Dec/2017 13:21:22] "POST /account/requestaccess/ HTTP/1.1" 200 3928
3
1
After I click the submit button it gives me the following:
[07/Dec/2017 13:33:59] "POST /account/requestaccess/ HTTP/1.1" 200 3776
None
None
Edit:
Changing the javascript to on('click' instead of on('change' produces the same value of None.
checkedlist = request.GET.getlist('report_id') is the culprit. You're populating that from the GET request, and when you POST, those aren't carried over in any way.
As a result, checkedlist is None and the save statement never fires.
After selecting a language in a language switcher form, I got a CSRF error:
The form is in base.html
<form action="{% url 'set_language' %}" method="post" class="form-inline">
{% csrf_token %}
<input name="next" type="hidden" value="" />
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-globe" aria-hidden="true"></i></div>
<select name="language" class="form-control" id="lang-switcher">
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}>
{{ language.name_local }} ({{ language.code }})
</option>
{% endfor %}
</select>
</div>
</div>
</form>
I submit the form with JS:
jQuery('#lang-switcher').change(
function(){
jQuery(this).closest('form').trigger('submit');
});
my template file art.html is as follow:
{% extends "base.html" %}
{% load staticfiles %}
{% load i18n %}
{% block content %}
....
{% endblock %}
views.py is as follow:
from django.template import RequestContext
from django.shortcuts import render_to_response
from .models import Exhibition, Picture
def index(req):
highlight = Exhibition.objects.latest()
exhibitions = Exhibition.objects.all()[1:]
return render_to_response('art.html', RequestContext(req,{'highlight': highlight, 'exhibitions': exhibitions}))
urls.py is as follow:
urlpatterns = [
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^admin/', admin.site.urls),
url(r'^art/', index),
url(r'^$', views.flatpage, {'url': '/home/'}, name='home')
]
I can load the page w/o problems, then when I submit the form to switch language I get the CSRF error.
edit
I must add that the form works well when I'm on root.
I finally solved it by using a different render function in my view:
return render(req, 'art.html', {'highlight': highlight, 'exhibitions': exhibitions})
I have a select form in django templates:
<form action="{% url "graph" document.docfile.name %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<select name="{{ document.docfile.name }}" id="{{ document.docfile.name }}" onchange="this.form.submit()">
<option value=""></option>
{% for document in documents %}
<option value="{{ document.docfile.name }}">{{ document.docfile.name }}</option>
{% endfor %}
</select>
</form>
I want to pick the selected file in views.py. I tried request.POST.get() with no success:
if request.method == 'POST':
doc = request.POST.get("name", "")
How can I grab the name of the selected file in python views.py?