How to retrieve data from a form in Django - django

I am working on a weather app where the client will be entering the name of the city in a search bar, and the name will be used to gain weather data from an API. To get the name of the city from the form, I have created this condition in view:
if request.method == 'POST':
city = request.data
print(city)
however when being printed, this error occurs: 'WSGIRequest' object has no attribute 'data'
What am I doing wrong? Or is there a completely different way to do this?

you must get data from template like this: (name of function in views.py is something same as in url.py.
def something(request):
if request.method == 'POST':
city = request.POST.get('data')
print(city)
data is the name of your input tag in template:
<input name='data'>
Update:
you need to have a action for your form. it includes a url. this url connect you to your view function for this form.
also you must add name to your input tag not your form tag.
template:
<form method="POST" action = "{% url "url_something" %}" >{% csrf_token %}
<div class="field has-addons">
<div class="control is-expanded">
<input class="input" type="text" placeholder="City Name" name="data" >
</div>
<div class="control">
<button class="button is-info" type="submit">
Search City
</button>
</div>
</div>
</form>
in url.py you must have a url like this.:
url(r'^something', views.something, name='url_something'),

Related

Django flash database object

I want to make an app where someone can search for something. When he searches he will get all of the things in the database that start with anything he wrote. I am using the messages framework.Here is the backend code:
def home(request):
if request.method == 'POST':
name = request.POST['name']
search = Team.objects.filter(name__startswith=name).all()
if not search:
messages.info(request, 'There wasnt')
else:
#looping all the items that search has
for i in search:
#flash the object
messages.info(request,i)
return render(request,'home.html')
And the HTML code:
{%if messages%}
{%for msg in messages%}
<div class='searching'>
#showing the name and the title of the object
<p style='color:white;margin-left:25px;'>{{msg.name}} {{msg.title}}</p>
</div>
{%endfor%}
{%endif%}
<form action='' method='post'>
{% csrf_token %}
<input class="form-control" type='text' name='name'>
<br>
<button class='btn btn-primary btn-lg'>OK</button>
</form>
But when I run it I don't get anything. Also I don't use extra_tags because I want the name and the title appear in the same div.
What should I do?
Pls can someone reply? I really need a help. Plsss.
Thanks.

How can I populate value of a hidden field in Django from the value of a range slider

So I am building an app that users are able to use a range slider to update a database with a new integer value. I have the slider which provides me with the integer value that I would like to return to the view, but I don't know how to return this value from the template.
https://docs.djangoproject.com/en/3.0/ref/forms/widgets/
I looked at the documentation but I couldn't find anything regarding range inputs.
# forms.py
from django import forms
class UpdateForm(forms.Form):
update = forms.IntegerField(widget=forms.HiddenInput(**something like:value='slider-input**}}))
# views.py
def home_view(request):
form = UpdateForm()
return render(request, 'main/index.html', {'form': form})
# index.html
...
<form id="update-form" method="post">
{% csrf_token %}
{{ form }}
<div id="slider">
<input class="slider-widget" min="0" max="25" step="1" value="0" type="range">
</div>
<div class="options">
<a href="{% url 'main-home' %}">
<img src="{% static 'main/media/cancel.png' %}" alt="cancel">
</a>
<button type="submit">
<img src="{% static 'main/media/confirm.png' %}" alt="confirm">
</button>
</div>
</form>
...
In it's simplest form you can take the slider value directly and do not need a HiddenField.
Your simple form
class UpdateForm(forms.Form):
update = forms.IntegerField()
In your html template just make sure that you add the 'name' attribute to your slider and give it the same name as the field name in your form:
<div id="slider">
<input name="update" class="slider-widget" min="0" max="25" step="1" value="0" type="range">
</div>
and in your view just process the form:
form = UpdateForm(request.GET or None)
if form.is_valid():
slider_value = form.cleaned_data['update']
# do somthing
Actually you do not really need a form for a simple case like this. You can also fetch the value directly in your view
slider_value = request.GET.get('update')

Django why request.method=='GET' when refreshing the page

I want to have some search boxes on my page and my related codes are like below, my problem is why when i refresh the page the if clause: " if request.method=='GET':" executes without i click on any button ?
def allstocks_view(request):
if request.method=='GET':
question_set =Stocks.objects.all().filter(confirm=_('approved') )
name=request.GET.get('namesearch')
number=request.GET.get('numbersearch')
brand=request.GET.get('brandsearch')
if name is not None :
question_set = question_set.filter(name__icontains = name)
if number is not None :
question_set = question_set.filter(number__icontains = number)
if request.GET.get("brandsearch"):
question_set = question_set.filter(brand__icontains = brand)
print(">>>>>>>>>>>>>>>>>>>>")
print(question_set)
template :
<form method="get">
{% csrf_token %}
<div class="">
<label for="namesearch">Name</label>
<input type="text" name="namesearch" >
<label for="numbersearch"> Number</label>
<input type="text" name="numbersearch" >
<label for="brandsearch"> Brand</label>
<input type="text" name="brandsearch" >
<label for="brandsearch"> City</label>
<input type="text" name="citysearch" >
<input type="submit" name="search" value="Search">
</div>
</form>
A refresh of a page is a GET request unless your last action was a POST request so that is going to execute every time. What you could do is make the form a post and handle in a request.method == 'POST' block. Another option if you wanted to continute with GET would be have your view take an optional parameter such as search=None and set up your urls accordingly. Then in your view you could check for if search exists instead of request.method == 'GET'.

access form data in view

I hava a form in my template which is for search.I did not made any form class to it. Is it possible to have access form data in view or should I make a form class to it.
<form class="navbar-form" role="search" action="{% url 'my_url_name' %}" method="get">
<div class="input-group add-on">
<input class="form-control" placeholder="search" name="srch-term" id="srch-term" type="text">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
I use this form for its style and I can not make this style with Form class
You can access form data in the request.GET (or request.POST if it is a post request) dictionary in your view. For example:
srch_term = request.GET.get('srch-term')
You can by using the QueryDict object you get with the request :
def myview(request):
if request.method == "POST":
data = request.POST
print(data['foo']) # <--Will print the value I entered into my form.
[...]
But be careful with this : There is no validation tool to ensure the data you receive is correctly formated.

Form data isn't submitted to the server

The following is all I have for the client server
<div>
<form action="/next/" role="form" method="POST">
{% csrf_token %}
<textarea class="form-control" rows="10"></textarea>
<input type="submit" value="submit"/>
</form>
</div>
and from the server(django) I just want to process the form.
def next(request):
request.body // nothing here except CSRF
request.POST // nothing here except CSRF
It's embarrassing, but what am I doing wrong?
It is not embarrassing. you just forgot name attribute in form element that you want to catch in backend.
<textarea name="element_name" class="form-control" rows="10"></textarea>
and in views.py
def next(request):
if request.method == "POST":
textarea_value = request.POST.get('element_name') # viola!
You forgot to add name attribute to the text area:
<textarea name="some_name" class="form-control" rows="10"></textarea>
Add a "name" attribute to the textarea ?