Dynamically change values based on user selected option django - html

I'm trying to change a value based on the exchange rate selected by the user within the <option> tag. I don't want to save the form result to the database. I just want it to dynamically change whenever the user changes the currency option.
Say a user selects a currency from the below form with the options in the view:
VIEW
def view(request):
currency_dict = {'EUR': 0.9154994049253867, 'JPY': 123.86706948640484, 'BGN': 1.7905337361530713, 'CZK': 22.375720955781375}
cur = currency_dict.items()
deposit = 10000
context = {
'currency_dict': currency_dict,
'cur': cur,
'deposit': deposit,
}
return render(request, 'coinprices/my-dashboard.html', context)
HTML - FORM
<div class="container">
<div>
<span>
<h1>My Dashboard</h1>
</span>
<span>
<form method="post">
<label>Choose Currency:</label>
<input list="ex-currency">
<datalist id="ex-currency">
{% for k, v in currency %}
<option value="{{ k }}"></option>
{% endfor %}
</datalist>
{% csrf_token %}
<button class="btn btn-outline-success btn-sm">Submit</button>
</form>
</span>
</div>
</div>
Then based on the users selection, multiply the {{ deposit }} value by the currency_dict[user_selected_currency] and change the bold text (see below):
DESIRED OUTCOME
<span>
<div><b>Total Investment {{ user_selected_currency }}</b></div>
<span class="text-xl">${{ deposit * currency_dict[user_selected_currency] }}</span>
</span>
Any ideas how this can be achieved?

Unfortunately, this is not a thing you can do with the render function you will need a GET request using ajax when the user changes the value, and then you can call a function based on the user option and return a valid response to the user this called "Chained Dropdown List" I found this amazing article that maybe can help you How to Implement Dependent/Chained Dropdown List with Django

Related

How to render update element (graph) with HTMX if two (2) elements (selector) have new value?

I have an element - dropdown list selector.
Which works and there is a choice of value.
Based on the value received, I send a request to execute the code and, at the end, to change / render another element (graph).
I added one more element to the template - one more selector list.
And also redirected the change route to this element in the template.
It also began to change based on the received value in the first selector list.
I'm thinking about how you can change the third element of the template (graph) - based on the values obtained - by the first and second elements (two selector lists).
The first selector list - refines filters the model query.
The second selector list - refines, filters the model request more precisely - the values ​​already left in the request after the first selector and already at the end sends the result to display in the form of a graph.
How can you think of changing only the schedule - rebuilding without changing the entire template?
Whether it is possible to think up such by means of HTMX?
zamer_tabl_2_htmx.html
<div class="row">
<div class="col-4">
<select
id="select-name"
class="custom-select"
name="select"
autocomplete="off"
hx-get="{% url 'zamer_tabl_2_htmx' %}"
hx-target="#figure, #selector_2">
{% for select in selector %}
<option value="{{ select }}">{{ select }}</option>
{% endfor %}
</select>
<hr/>
<div id="selector_2" class="col-8">
{% include 'zamer_tabl_2_htmx_select.html' %}
</div>
</div>
<div id="figure" class="col-8">
{% include 'zamer_tabl_2_htmx_figure.html' %}
</div>
</div>
zamer_tabl_2_htmx_select.html
<select
id="select-name-2"
class="custom-select"
name="select_2"
autocomplete="off"
hx-target="#figure">
{% for select_2 in selector_2 %}
<option value="{{ select_2 }}">{{ select_2 }}</option>
{% endfor %}
</select>
views
def zamer_tabl_2_htmx(request):
///code///
if request.htmx:
print("HTMX")
if request.htmx:
print("HTMX")
print(select_kotol)
return render(request, 'zamer_tabl_2_htmx_select.html', context)
return render(request, 'zamer_tabl_2_htmx_figure.html', context)
return render(request, "zamer_tabl_2_htmx.html", context)

Django forms widgets Textarea is directly set to type hidden but need it visible

My problem is i set a form from a model to change the value of the field "description" of this model :
Model :
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
birth_date = models.DateField(null=True, blank=True)
profile_img = models.ForeignKey(Image,on_delete=models.CASCADE,related_name='images',null=True)
description = models.TextField()
Form :
class ChangeUserDescription(ModelForm):
class Meta:
model = Profile
fields = ['description']
widgets = {
'description': forms.Textarea()
}
labels = {
'description':'Description'
}
template :
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Save changes</button>
</form>
But in result of this code I obtain this :
<input type="hidden" name="csrfmiddlewaretoken" value="brsd4oO0qhMw2K8PyCIgSgEMqy7QFvEjTHaR6wTJmyWffJaCX5XyOMDLrGldZ3ji">
<button type="submit">Save changes</button>
The issue is that i get : type="hidden" in the input whereas i want it to be visible and i do not specified in the widgets that it must be hidden.
The hidden input field that you are referring to is the following:
<input type="hidden" name="csrfmiddlewaretoken" value="brsd4oO0qhMw2K8PyCIgSgEMqy7QFvEjTHaR6wTJmyWffJaCX5XyOMDLrGldZ3ji">
This is Django's CSRF token, which you have correctly included in your form, and should always be an <input type="hidden".
You have not shown us your template code, but as long as you correctly pass the form variable to your template, the following code should work:
<form method="post">
{% csrf_token %}
Please enter your description here: {{ form.description }}
<button>Submit</button>
{% if not form %}
You have forgot to add the <tt>form</tt> variable to your template!
{% endif %}
</form>

Django , How can I set the default value to today of input date(not using forms)?

I'm using django to make website.
I succeded remaining the input date value after submit passing the value.
But I don't know how I can remain the selected value after submit. (I'm not using form)
Also, I want to know how I set the default value to today of input type="date"!
Here's my page. I want to keep remain the selected value after submit( after submit, the page return this page again)
sales.management.html
<form id="sales_search" action="{% url 'management:sales_search' %}" method="GET">
<select title="team_choice" name="team_choice" class="select" id="team_choice">
<option name='FC' value="FC" {% if team =='FC' %} selected {% endif %}>FC</option>
<option name='Fitness' value="Fitness" {% if team =='Fitness' %} selected {% endif %}>fitness</option>
<option name='Pilates' value="Pilates" {% if team =='Pilates' %} selected {% endif %}>pilates</option>
<option name='All' value="All" {% if team =='All' %} selected {% endif %}>all</option>
</select>
<span>Start Day: <input type="date" class="startdate" name="startdate" value="{{ startdate }}" ></span>
~<span>End Day: <input type="date" class="enddate" name="enddate" value="{{ enddate }}" ></span>
<button type="submit" class="btn btn-info" value="search" >search</button>
</form>
I tried {% if team =='FC' %} selected {% endif %} in select boxes.
But, it gets error Could not parse the remainder: '=='FC'' from '=='FC''.
views.py
def sales_search(request):
team_choice = request.GET.get('team_choice','')
startdate = request.GET.get('startdate','')
enddate = request.GET.get('enddate','')
#Todo ( it's a long)
context = {
.... ,
'startdate' : startdate,
'enddate' : enddate,
'team':team_choice, }
return render(request, 'management/sales_management.html', context)
How can I keep the selected value after submit and How can I set the default value to today of input date?
Any help will be very helpful to me, thanks!
in your models you can add DateField(default=date.today)
references:https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.DateField
you need to put a space between == and 'FC' in your template.
And to set the default date to today in your views file add
import datetime
and in your context write:
context = {
.... ,
'startdate' : startdate if startdate else datetime.date.today(),
'enddate' : enddate if enddate else datetime.date.today(),
.....
}

Error retrieving multiple select option in Django

I have a drop down with multiple select option in my html page. On form submission, I am trying to capture all of the selected options by user in that drop down. but it throws me an error instead "TypeError:'instancemethod' object is not subscriptable". Following is my template.html and views.py
Template.html:
Select packages:
<form name=automationForm action="/vsawebauto/automation/results/" method="post">
//some form elements
<select id="package" name="package[]" multiple="multiple" size="5">
{% for i in ida.package_set.all %}
<option value="{{ i.pkg_id }}">{{ i.display_name }}</option>
{% endfor %}
</select>
//some form elements
<input type="submit" id="submit" value="Submit Job" />
Views.py:
def results(request):
//some code
selected_packages = request.POST.getlist['package[]']
//some code
return HttpResponse("Selected Packages:"+selected_packages)
Note: I debugged the code as well. The request.POST object has multiple selected values. For eg. when 1 and 701 packages are selected by user, request.POST has 'package[]': ['1','701']. But the code fails when I do request.POST.getlist['package[]']
request.POST.getlist['package[]']
Should be
request.POST.getlist('package[]')
Replace [] with () which was the cause of the error.
Here is the documentation and usage of getlist.
Also, change
return HttpResponse("Selected Packages:"+selected_packages)
to
return HttpResponse("Selected Packages: %s" % selected_packages)

dropdown menu html code with select options from django

My HTML code is below:
<select name="txn" tabindex="3" id="txn" class="fixed" onfocus="highlightInput(this.id)" onblur="unhighlightInput(this.id)">
<option value="RR" my="{{txn|genselected:"RR"|safe}>RR</option>
<option value="CR" my="{{txn|genselected:"CR"|safe}}">CR</option>
<option value="SR" my="{{txn|genselected:"SR"|safe}}">SR</option>
<option value="OR" my="{{txn|genselected:"OR"|safe}}">OR</option>
</select>
txn is defined in forms.py as:
txn = forms.ChoiceField(label="txn", choices = it_const.TXN),
My Question:
The option values are dynamically increasing in the database? i Want to read the option values from the database and put them in dropdown menu in html. Can you please help me with HTML code and how to read the options from txn form field and display it in menu options.
Thanks in advance.
views
def view_name(request):
form = OptionForm()
options = Option.objects.filter()
return render(request, 'page.html', {
'form': form,
'options': options,
})
html
<form method="post">
{% csrf_token %}
{{form}}
<input type="submit" value="Submit">
</form>
{% for option in options %}
<p>{{option.field}}</p>
{% endfor %}
You can retrieve the database values in the view file, and then add them to an array, and then render the array as option for form field.
TXN_choices = Options.objects.all()
#and then run a for loop to dynamically generate the options array:
TXN = (
('x', 'xxx'),
('y', 'yyyy'),
)
and then render the ModelForm.