What is the simplest way to get user input in Django? - python

I want to get some user input, process it a little and present the same to the user. I need not save the inout to the database. What is the simplest way to do that in Django

In the html template
<form method="POST">
{% csrf_token %}
{{ form.name of field in forms.py }}
</form>
In the views.py
if request.POST:
form = formName(request.POST)
if form.is_valid():
variable: form.cleaned_data['name of field in forms.py']

this is a simple example
views.py
def test_form(request):
if request.method == "POST":
user = request.POST.get('username')
if user == "mark":
return HttpResponse('hello mark')
return render(request, "form.html")
urls.py
path ('form/', test_form, name="form")
form.html
<form method="POST" action="{% url 'form' %}">{% csrf_token %}
<input type="text" name="username">
<input type="submit" name="submit">
</form>

Related

Two HTML Forms in one DJango views

I have two simple HTML forms on one page. I want to create Django view to submit multiple Django forms. I can submit form1 but I have no clue how to submit form2.
There is lot of material on internet but they are all about Djanog forms. Please help me with HTML form submission.
HTML Form
<form action="" method=post name="form1" id="form1">
<input type="text" id="input_form1" name="input_form1">
<button type="submit">Submit</button>
</form>
<form action="" method=post name="form2" id="form2">
<input type="text" id="form2" name="form2">
<button type="submit">Submit</button>
</form>
Views.py
def index(request):
if request.method == 'POST':
input_form1 = request.POST.get('input_form1')
return render(request, 'index.html', params)
Please elaborate how to integrate form2 in Views.py
you can put hidden input inside of each form to identify them
index.html
<form action="" method="post">
{% csrf_token %}
<input type="text" id="input_form1" name="input_form1">
<button type="submit">Submit</button>
<input type="hidden" name="which_form_is_it" value="this_is_form_1">
</form>
<form action="" method="post">
{% csrf_token %}
<input type="text" id="input_form2" name="form2">
<button type="submit">Submit</button>
<input type="hidden" name="which_form_is_it" value="this_is_form_2">
</form>
views.py
def index(request):
if request.method == 'POST':
#watch output in console
print(request.POST)
which_form_is_submiting = request.POST["which_form_is_it"]
if str(which_form_is_submiting) == "this_is_form_1":
#here is yor logic for data from form 1
form_1_input = request.POST["input_form1"]
if str(which_form_is_submiting) == "this_is_form_2":
#here is your logic for data from form 2
form_2_input = request.POST["input_form2"]
return render(request, 'index.html', params)

Don't return forms in context if they are not altered?

In my HTML-file I have a submit button (click_button) to do stuff and a submit button for a Django form (form_submit).
All submits are redirected to one View-function (get_post_from_submit). If using the return render() function, I always have to return the context including the form, but I have no information of the form when I pressed the click_button.
Is there any way to not return the form again?
home.html
....
<body>
{% load bootstrap4 %}
<form action="" method="POST" novalidate>
{% csrf_token %}
{% bootstrap_form form %}
</form>
<form action="" method="POST" novalidate>
{% csrf_token %}
<button class="btn btn-primary" name="click_button" type="submit">Grafik</button>
</form>
</body>
....
views.py
def get_post_from_submit(request):
if request.method == 'POST':
if "book_field" in request.POST:
# Do Stuff
form = form_book(request.POST)
if "click_button" in request.POST:
# Do Stuff
# Here the form always gets a reset, because I have no Info about the form in POST but it is needed as context...
form = form_book()
return render(request, 'home.html',{"form": form})
One method would be to encapsulate just one form tag across both sections.
<form action="" method="POST" novalidate>
{% bootstrap_form form %}
<input type="submit" name="action" value="FormSubmit"/>
{% csrf_token %}
<input type="submit" name="action" value="Grafik"/>
</form>
Using name="action" you can differentiate the POST action in the view like so:
def get_post_from_submit(request):
if request.method == 'POST':
form = form_book(request.POST)
if request.POST['action'] == 'FormSubmit':
[...]
elif request.POST['action'] == 'Grafik':
[...]
return render(request, 'home.html',{"form": form})
The form_book will no be able to retain the form data whenever the Grafik POST type is send to the view.

Basic Django form response

I am new to Django and looking to build a quick form with a response.
I am trying to build a form which would ask the user to input his name when the user clicks submit the page should reload and just say "Hello .
urls.py
class Question1Form(forms.Form):
n = forms.CharField(max_length=100,
widget=forms.TextInput(
attrs={'placeholder': 'Number', 'class': 'form-control'}))
views.py
def home(request):
if request.method == 'POST':
form = Question1Form(request.POST)
if form.is_valid():
result = [Question1Form.ans()]
return HttpResponse(Question1Form.n)
else:
form = Question1Form()
return render(request, 'index.html', {'form': form})
index.html
<form action="" method="post" class="form">
{% csrf_token %}
{{ form.non_field_errors }}
<div class="form-row form">
<div class="col-sm-4">
{{ form.n.errors }}
{{ form.n }}
</div>
<input class="btn btn-primary" type="submit" value="Submit" />
</div>
</form>
So how the code s
You should call instance field, not class field and get value from validated(cleaned) data (see documentation):
return HttpResponse(form.cleaned_data['n'])
If you want to reload the same template with n value:
return render(request, 'index.html', {'form': form, 'n': form.cleaned_data['n']})
and at the template add:
{% if form.is_valid %}
<p> Hello {{ n }} </p>
{% endif %}
if request.method == 'POST':
form = Question1Form(request.POST)
if form.is_valid():
result = form.save()
return render(request, 'index.html', {'created': True})
Then in your HTML you can say
{% if created %}
<p> Hello </p>
{% endif %}
edit I see now you have no action in your form.
So you need to point to that view in your URLS.py.
for example.
from myapp import views as app_views
from django.conf.urls import url
urlpatterns =[
url(r'^my_form/$', app_views.home, name='save_form'),
]
And then add the action to your form.
<form action="{% url 'save_form' %}" method="post" class="form">

View not receiving POST data from image upload page

I've seen similar questions but can't figure this out, I have a program that upload pictures on a model:
views.py:
def upload_pic(request):
if request.method == "POST":
image_form = ImageUploadForm(request.POST, request.FILES)
if image_form.is_valid():
image_form.save()
return HttpResponse('success')
else:
return HttpResponse('fail')
return render(request, 'tracker/upload_pic.html', {"image_form": image_form})
template:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<body>
<form method="POST" enctype="multipart/form-data">{% csrf_token %}
{{ image_form.img }}
<input type="submit" value="submit" />
</form>
</body>
</html>
urls.py:
urlpatterns = [
url(r'^upload_pic', views.upload_pic, name='upload_pic')
]
Just trying to save to the user model so I can retrieve it later, but I can't access any POST data, I've also tried add action = "{% url upload_pic %}" to my form in the HTML template, but I get the NoReverseMatch error
class ImageUploadForm(forms.ModelForm):
#model to store the information about the pictures
class Meta:
model = ExtendedProfile
exclude = ()
You need to add action on your form so it will retrieve the url name.
<form action="{% url 'upload_pic' %}" method="POST" enctype="multipart/form-data">{% csrf_token %}
{{ image_form.img }}
<input type="submit" value="submit" />
</form>
You forgot the '' on upload_pic.

django-why this form is always invalid

i have created a form with minimal fields(for testing) , but it never enters form.is_valid()
Here is the minimal code
in the models.py
from django.db import models
class sample(models.Model):
field1=models.CharField(max_length=100)
field2=models.CharField(max_length=100)
in the forms.py
from django.forms import ModelForm
from app.models import sample
class someform(ModelForm):
class Meta:
model=sample
in the views.py
some imports
def index(request):
return render(request, 'app/index.html')
def contact(request):
if request.method=='POST':
form=someform(request.POST)
if form.is_valid():
field1=form.cleaned_data['field1']
field2=form.cleaned_data['field2']
return HttpResponse("valid")
else:
return HttpResponse("invalid")
else:
form=someform()
return HttpResponse("error")
The problem is , it never enters (if form.is_valid()) . Am i missing something ? please help
in the index.html
<html>
<body bgcolor="#2E9AFE">
<form action="contact" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" id="field1" name="field1">
<input type="text" id="field2" name="field2">
<input type="submit" id="submit" name="submit">
</form></body></html>
First pass your form to index.html, when the request is not POST in views.py:
else:
form=someform()
return render(request, 'index.html', locals())
In template you should make it like this:
<form action="contact" method="POST" xmlns="http://www.w3.org/1999/html">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn">Submit</button>
</form>
When receiving the POST query, Django is looking for the 2 fields of IDs id_field1 and id_field2, litteraly, thus your HTML is to be the following:
<html>
<body bgcolor="#2E9AFE">
<form action="contact" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" id="id_field1" name="field1">
<input type="text" id="id_field2" name="field2">
<input type="submit" id="submit" name="submit">
</form>
</body>
</html>
Another solution is to use the {{ form.as_p }} or {{ form.as_table }} to render the inputs inside or tags automatically.
You could also add {{ form.non_field_errors }}, {{ form.field1.errors }}, and {{ form.field2.errors }} in your current HTML to display the form errors when validation fails.

Categories

Resources