Django Forms to values of html <input> field - django

I am trying to access the values of a Bootstrap btn-group from Django and from the documentation I have found, it seems that you should use Forms in Django for such tasks.
This is what the html looks like, right now:
<div class="col-md-6">
{% for metric in metrics %}
<input name="{{ metric.name }}" type="hidden" value="0"/>
{% endfor %}
<div class="btn-group" data-toggle="buttons">
{% for metric in metrics %}
<button type="button" class="btn btn-default" data-checkbox-name="{{ metric.name }}">{{ metric.name }}</button>
{% endfor %}
</div>
</div>
How can I use forms to get the values of the input fields?

Here it is a basic example about using a form in django
views.py:
#login_required
def your_view(request): # Add this code into your view
if request.method == 'POST':
# So here you can do a loop over POST fields like this
data_list = [] # We will insert all the inputs in this array
for key in request.POST:
data_list.append(request.POST[key])
# Here you can manage the the data_list and do whatever you need
# The content of the data_list depend on your inputs
# It could be string, integer....
# YOUR VIEW CODE
template (form example):
<form action="." method="post" id="add_user_form">
{% csrf_token %}
{% for metric in metrics %}
<input type="text" name="{{ metric.name }}" placeholder="whatever you want">
{% endfor %}
<input type="submit" value="submit" class="default"/> # Submit button
</form>
{% csrf_token %} : You need to put this in every form you use
action="." : This make the post to the actual page
But anyway I strongly recommend you to check this Django Forms Documentation to unterstand better the logic, and also check the ModelForms because can save you a lot of time when you need to make a form for a model that exists in your Django Models

You are'n forced to use django forms, this is just a way to get a sort of organization.
in you views toy can get the values sent to the server by using request.GET or request.POST, depending of the method of the form.
to get a list of values you have received just do a
print request.POST
request.POST is a dictionary, so you can get any value fron them by its key:
print request.POST['<key>']

Related

Passing HTML tag data- to Django with form submit

I am trying to pass data in HTML tag with a form submit to Django
I currently have a template like this:
{% for item in items %}
<div class="product">
{{ item.item_name }}
<form method="POST">
{% csrf_token %}
<input
type="submit"
value="add to cart"
data-pk="{{item.pk}}"
class="add_product"/>
<form>
</div>
{% endfor %}
I want to pass data-pk with a Django form. How do I do that?
Also I know, I can create a view to handle endpoint to do that, and include pk in the url, is that a better solution?
I am new to Django, and I will be grateful for any input on how to do stuff the right way
Instead of data, use value={{item.pk}} and handle the submit logic in your view.

Django - do not validate the second form

I have this code snippet in template.
<form method="POST" novalidate>
{% csrf_token %}
{{ form }}
{{ form2.as_p }}
<button type="submit" class="btn btn-secondary">Search</button>
</form>
And in forms.py there are two forms (not ModelForm, but only Form).
form searches data in first db and form2 search data in second db and displays the results. The second form has only one field and I'd like to have something like this in
a view.
if request.method == "POST":
if form.is_valid():
# extract data from the first db
if form2.is_valid()
# extract a few more data from the second db
The field in the second form is not required for the user to fill in. If the user fills it in the user gets only more data displayed.
I solved it partially with the novalidate in HTML. But what I'd like to have is the validation of the first form and the second form with its one form field can be empty.
Is there some django feature to achieve this result?
something like this?
<form method="POST">
{% csrf_token %}
{{ form.novalidate }}
{{ form2.as_p }}
<button type="submit" class="btn btn-secondary">Search</button>
</form>

Django filter for result from checkbox form

I'm begginer of django and i try to implement search engine to look for recipes that contains selected ingredients.
I want to do form with all ingredients_type from my Model and user can select up to 3 of them (checkbox prefered). Then i want to filter recepe that contains them.
I was looking for generic form but never get right result.
Right now i have only a scratch and Im looking for any advice
model.py
class IngredientsType(models.Model):
type = models.CharField(max_length=60, blank=True)
def __str__(self):
return self.type
search.html
{% for ingredients in ingredients_type %}
<input type="checkbox" id="{{ingredients.type}}">
<label for="{{ingredients.type}}">{{ingredients.type}}</label>
{% endfor %}
<form method="POST" action="#">
<button type="submit" name="save" value="save">szukaj</button>
</form>
Do i have to create custom form or there is good way to use some of generic form?
I think what you are on the right path, but there are some mistakes in your code.
search.html
<form method="POST" action="">
{% csrf_token %}
{% for ingredients in ingredients_type %}
<input type="checkbox" id="{{ingredients.type}}" value="1">
<label for="{{ingredients.type}}">{{ingredients.type}}</label>
{% endfor %}
<button type="submit" name="save" value="save">szukaj</button>
</form>
model.py
You might want to use many-to-many relationship to represent to relation between the ingredient types and the recipes.
views.py
Make sure you have the POST handling method to work with your filter query. This should get data from the form.

How to make a selection button inside a multistep form wizard in Django that renders an output without proceeding to the next step?

I am new to Django and I am making a project with a multistep form using django-formtools. The problem is, in my step 2 form, I have selection fields that I need to pass in the backend to perform some calculations and then render the output. The user can make changes anytime based on the output. I made an apply changes button which should trigger the backend process and a proceed to next step button if the user decides to finalize the selected changes. However, when I click the apply changes button, it leads me to the next step instead.
Here's my HTML code:
<form action="" method="POST">
{% csrf_token %}
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{ form }} # three selection fields
<button name="apply_changes">Apply Changes</button>
{% endif %}
{% if wizard.steps.prev %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans '‹ Previous Step' %}</button>
{% endif %}
<input type="submit" value="{% trans 'Finish' %}">
</form>
Here's my SessionWizardView method code snippet:
def get_context_data(self, form, **kwargs):
context = super(StepWizard, self).get_context_data(form=form, **kwargs)
if self.steps.current == 'step_1':
# save step 1 data to sessions
if self.steps.current == 'step_2':
step1_data = self.get_all_cleaned_data()
# if apply changes button is clicked
data = self.request.POST.get('apply_changes')
# process data
# add output to context
return context
I need help on how can it rightly be done. Thanks in advance!
So for future django developers who encountered the same problem as me, here's the answer to my question:
1) validate the data in step 2 which is temporarily the default values of my selection fields; and
2) override the post method to load the current page using the goto_step wizard function and embed it in the apply changes button
You can find the guide here :)
And then there 'ya go! Once the user clicks the apply changes button, the page reloads and the output is rendered in the form.
Still needs to optimize it though :D

How do I change the template being displayed after the user clicks a button?

I'm quite new to Django, so I aplogize if I am making dumb mistakes.
Here is the code I have so far:
For views.py:
def bylog(request):
if request.POST.get('Filter'):
return render(request, 'index.html', context)
filtered_login = Invalid.objects.values_list('login').distinct()
filtered = []
for item in filtered_login:
filtered.append(item[0])
results = {'results': results, 'filtered': filtered}
return render(request, 'bylog.html', context)
Here is a snippet of bylog.html:
<select id>"dropdown">
{% for item in filtered %}
<option value={{ item }}">{{ item }}</option>
{% endfor %}
</select>
<input type="submit" value="Filter" name="Filter" />
My main goal is to get the value from the drop down list, and after the user clicks the Filter button, the value gets passed to another template.
Is that even possible?
Thanks for you help.
The basic for your goal I supose it is to manage POST in django, meaning that you want to send any data/variables from a template to a view and then do any operation with it (send it to another template, or store...)
The basic for this is(Using HTML form, not Django form):
- Create a HTML form in the template
- Add the selects/inputs with the data you want to manage and a button/input to make the post
- Manage the post in the view
EXAMPLE
template form
<form id="" method="post" action=".">
{% csrf_token %}
<select id="any_name" name="any_name">"dropdown">
{% for item in filtered %}
<option value={{ item }}">{{ item }}</option>
{% endfor %}
</select>
<input type="submit" value="Filter" name="Filter" />
</form>
view.py
def your_view(request):
if request.method == 'POST': # If anyone clicks filter, you receive POST method
data = request.POST['any_name']
# Do what you need here with the data
# You can call another template and send this data
# You can change any_name for the variable you want, changing the name and id in the select
#Your view code
I recommend you to read about Django forms because if you need a bigger form, to manage the data of a model with a lot of fields, a Django Form will save you a lot of time
Working with Django Forms