I am trying to figure out a way in Django to maintain the selected value in a dropdown menu, after the page refreshes. Here is the current code I have. Whenever I make a selection the page refreshes, showing the correct data associated with the selection, but defaults to the name of the top selection in the dropdown menu. Thanks for the help.
<html>
<form method="GET" action=".">
<select name="option-menu" id="option-menu">
<option value="" disabled selected>Choose a Name</option>
{% for d in database %}
<option value="{{d.name}}">{{d.name}}</option>
{% endfor %}
</select>
<button type="submit" class="btn-filter">Filter</button>
</form>
</html>
--views.py--
option_menu = request.GET.get("option-menu")
qs = Database.objects.filter(database_id=id)
if option_menu != '' and option_menu is not None:
qs = qs.filter(name__icontains=option_menu)
return render(request,
template_name='main/database.html',
context={"queryset": qs
})
You could create a function in your template that activates periodically, or on the click of a specific element that sends the selection to the view which saves it to a cache file.
Function to check the selection:
<script>
function saveSelection() {
var selection
selection = $('#option-menu').val()
dict = {}
dict[selection] = selection
$.ajax({
url: '//' + '' + '/' + '' + "/",
type: 'POST',
headers: {'X-CSRFtoken': '{{ csrf_token }}'},
data: dict,
dataType: 'json'
})
}
</script>
You'll need to populate your own url in here, I couldn't glean it from your code above
In your view, you have a if statement to handle POST requests to save the selection, and you pass the selection into your context with a try block
try:
savedInfo = {}
csv_reader=csv.DictReader(saveFile)
for row in csv_reader:
if row['Selection'] == "Your selection text index 0":
selection = 0
elif row['Selection'] == "Your selection text index 1":
selection = 1
savedInfor[row['Selection']] == row['Selection']
context['saveInfo'] = savedInfo
except:
pass
if request.method == "POST":
data = request.POST
#save data
Then, on page load, you need a function to change the selection from the default value to the saved one
{% for info, value in saveInfo.items %}
<script>
$('document').ready(function(){
$('#option-menu').prop('selectedIndex', '{{value.1}}'
</script>
This probably isn't a perfect method for this, but it may push you in the right direction
Related
i'm new at django template. i have a search field in header and i want to send searched keyword in this format
search/q/{{keyword}}/
my html code is this
<form action="{% url 'content.search' q=searched_key %}" class="search-input">
<input type="text" name="searched_key">
<button type="submit"><i data-feather="search"></i></button>
</form>
i want to get input value and send but result url is this
http://127.0.0.1:8000/contents/search/q//?searched_key=test
how can i do it in right way?
you can POST your search value as form (don't need to use /search/q//?searched_key=test in url) and your view should be something like this:
def search_view(request):
if request.method == "POST":
search_key = form.save()
search_result = Content.objects.filter(key=search_key)
context = {
'results': search_result,
}
return render(request, 'content.html', context)
You're probably better off using javascript to accomplish this.
<form id="form-id">
<input type="text" id="searched_key" name="searched_key">
<button type="submit"><i data-feather="search"></i></button>
</form>
<script type="text/javascript">
function submitForm(e) {
// Prevent default form submit
e.preventDefault();
// Get the search query
let query = document.getElementById("searched_key").value;
// redirect to the url with the query appended
window.location.href = "/contents/search/" + query + "/";
return false;
}
// Add an event listener to the form when the page loads
window.addEventListener('load', function() {
document.getElementById("form-id").addEventListener('submit', submitForm);
});
</script>
So I have a button that is suppose to "Add" an "Item" to a list and update the list on the same page without refreshing it.
Adding the Item without redirecting worked. but the element is not refreshed properly
Here is my script:
<div id="list">
{% for item in items %}
{{ item.name }}
{% endfor %}
</div>
<button id="add" type="submit">+</button>
<script>
$('#add').click(function () {
$.get('/url/page/', function (data) {
$('#list').html(data);
});
});
</script>
views.py
def add_to_list(request, item_id, list_id):
item, created = List.objects.get_or_create(list_id=list_id,
item_id=item_id)
return HttpResponse(request)
I feel like I have to add something in the views? and maybe use json code?
You should append the result of your request to the div element. Try this:
$('#add').click(function () {
$.get('/url/page/', function (data) {
$('#list').append(data);
});
});
Assuming that data that you receive from GET request is not an object but just a string. If it is an object add data.name:
$('#list').append(data.name)
Hope it helps.
So I have a form in my HTML that looks like this:
<form id="passer" method="POST" action="{% url 'Sizer:printView' %}">
{% csrf_token %}
<input type="hidden" id="vals">
<input type="submit" value="Print all selected items" id="printBut">
</form>
With this form what I wish to achieve is when the submit button is clicked my jQuery will calculate a value and put it into the vals field in the form, then I want it to post to the printView view (to get the calculated data into a view) then once the data has been post render a new template and pass in the data calculated by the jQuery.
My printView (where the data is being posted) looks like this:
def printView(request):
to_print = str(request.POST.get('vals'))
template = "Sizer/printview.html"
context = {'to_print':to_print}
return redirect('requested_print_data', to_print)
And my requested_print_data view (where I want to render my new template) looks like this:
def requested_print_data(request):
all_data['to_print'] = #Dont know how to get my variable
template = "Sizer/printdata.html"
context = {'all_data':all_data}
return render(request, template, context)
So at the moment what happens is when the form is submit, the value is calculated and stored into the form, the URL will gain the extra part from where it's being posted (www.example.com/printables ---On Submit---> www.example.com/printables/printview/) but the template will remain the same.
I have been stuck on this for a day or two now so any help would be greatly appreciated!
EDIT: jQuery as requested:
$('#passer').submit(function(){
console.log("Inside click");
var selected = [];
var $vals = "";
$('.datatable').find('input[type="checkbox"]:checked').each(function(){
selected.push($(this).attr('value'));
});
$.each(selected, function(index, val){
$vals+= val + ',';
});
console.log($vals)
$("#vals").val($vals)
You can render the out put in the printView itself. No need to write another view. Change your printView to
def printView(request):
to_print = str(request.POST.get('vals'))
template = "Sizer/printdata.html"
context = {'all_data':to_print}
return render(request, template, context)
I am new to django. I need to put conditional drop-down on my web app based on the radio button selected by user in form. The idea is that based on radio button selection by user another drop-down should be populated on the form. This drop down will be a from a list of values that will be retrieved from database. The final value selected from this drop-down will do the main operation by pressin separate buttons. Please suggest how to do that. An example or link will surely help. Thanks
My example code is
<script>
function my_radio_select() {
var1 = document.getElementById("radio1");
var2 = document.getElementById("radio2");
var3 = document.getElementById("radio3");
if (var1.checked === true) {
window.location.href = "A.html";
}
else if(var2.checked === true) {
window.location.href = "A.html";
document.myform.action = "A.html";
}
else if(var3.checked === true) {
window.location.href = "A.html";
}
}
</script>
<br>
<br>
<br>
<input type="radio" id="radio1" name="project_type" value=0 checked onclick="my_radio_select();">
<label>Projects I own</label>
<br>
<input type="radio" id="radio2" name="project_type" value=1 onclick="my_radio_select();">
<label>Projects I manage</label>
<br>
<input type="radio" id="radio3" name="project_type" value=1 onclick="my_radio_select();">
<label>Projects I can edit</label>
{% endblock %}
class MyProjForm(ModelForm):
existing_projs = CSProj.objects.all()
choices_int = tuple((p.name, p.name) for p in existing_projs)
#tech = forms.ChoiceField(label='Existing Projects' ,widget=forms.Select(attrs={'class':'form-control'}),choices=choices_int,required=True)
tech = forms.ChoiceField(label='Existing Projects' ,widget=forms.Select(attrs={'class':'form-control'}),choices=choices_int,required=False)
class Meta:
model = CSProj
fields = ['name','user_workspace', 'compiler_path','ccs_path','tdk_path']
exclude = ('name','user_workspace', 'compiler_path','ccs_path','tdk_path')
def __init__(self, *args, **kwargs):
if 'user' in kwargs:
user = kwargs.pop('user')
super(MyProjForm, self).__init__(*args, **kwargs)
### Done to refresh choices as soon as it is added
existing_projs = CSProj.objects.filter(owner_id=user)
choices_int = tuple((p.name, p.name) for p in existing_projs)
self.fields['tech'].choices=choices_int
If you want to do all the stuff without reloading the page you need to use ajax. Django will only render the form for you.
1) Render all the required fields in a form (or two forms).
2) Hide those fields (or form) that should appear only if the radio button is checked (Using JS, jQuery).
3) Show the hidden stuff and get the necessary values from db using ajax as the radio button is checked.
I'm trying to launch a modal if my flask-wtf form validation fails. The code snippet below otherwise works as expected other than it launches the modal even when I load the form before submission (appears that form.errors initialises to False before form is submitted).
What do I need to change get the modal to show iff form is submitted and form validation is successful?
<script>
var formSuccess = {% if form.errors %}false{% else %}true{% endif %};
$(document).ready(function() {
if (formSuccess) {
$('.modal').modal('show');
}
});
</script>
I resolved this by passing a validation_success variable when checking
if form.validate_on_submit() within the calling routine. I then pick this value up using jija:
<script>
var formSuccess = {% if validation_success %}true{% else %}false{% endif %};
$(document).ready(function() {
if (formSuccess) {
$('.modal').appendTo("body").modal('show');
}
});
</script>