This html template from my online class executes as intended, but why? It seems like it is executing out of order:
It calls my python form class using Django's syntax {{form}} to inject the blank fields for the user to fill out (name, email, textbox)
The user can enter and hit the "Submit" button
but then (confusingly) is that it seems the {{form}} class is called again with the entry information as it then successfully prints out user input to the terminal. Why is this?
html in templates.py
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<h1>fill out the form</h1>
<div class="container">
<form method="POST">
{{form}}
{% csrf_token %}
<input type="submit" class="btn btn-primary" value="submitme">
</form>
</div>
</body>
</html>
Form class in views.py
def form_name_view(request):
form = forms.FormName()
if request.method == "POST":
form = forms.FormName(request.POST)
if form.is_valid():
print("VALIDATION SUCCESS")
print("NAME: " + form.cleaned_data['name'])
print("EMAIL: " + form.cleaned_data['email'])
print("TEXT: " + form.cleaned_data['text'])
return render(request, 'first_app/form_page.html', {'form' : form})
Supplemental: the url that uses the html template and my forms class
from django.urls import path
from first_app import views
urlpatterns = [path('formpg', views.form_name_view, name = 'formpg')]
As mentioned in the Django form docs,
Form data sent back to a Django website is processed by a view, generally the same view which published the form. This allows us to reuse some of the same logic.
So your code is executing in the correct order:
When the page is first loaded, a GET request is made and form_name_view() is called. This creates an empty Form object and renders it into a html form with render(request, 'first_app/form_page.html', {'form' : form})
When the html form is submitted, a POST request is made and a new Form object is made with the data sent from the web browser. As in the example, you may want to direct users to another page if their submitted form is valid.
Related
I need to get data from input and write it to query variable. When I click to search button I need write data in query variable. How can I do that? I mean click event and write data in query.
This is my code:
views.py:
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
if request.method == 'GET':
return render(request, 'index.html', context={})
# Handles the search once the submit button in the form is pressed
# which sends a "POST" request
if request.method == 'POST':
# Get the input data from the POST request
search_query = request.POST.get('search', None)
# Validate input data
if search_query and search_query != "":
try:
from googlesearch import search
except ImportError:
print("No module named 'google' found")
for j in search(search_query, tld="co.in", num=10, stop=1, pause=2):
print(j)
else:
return HttpResponse('Invalid input.')
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form method="POST">
{% csrf_token %}
<input type="text" name="search" placeholder="some text"><br>
<button class="button" name="submit" type="submit">Search</button>
</form>
</body>
</html>
urls.py
from django.urls import path
from firstapp import views
urlpatterns = [
path('', views.index, name='home')
]
All files are in hello folder. My app namely firstapp path: C:\Users\user\Desktop\hello\firstapp
index.html path is:
C:\Users\user\Desktop\hello\firstapp\templates
We will need to change the index() function to handle POST or GET methods (refer to https://www.w3schools.com/tags/ref_httpmethods.asp for more information on GET and POST requests), by default django always listens to a GET request. You can know whether or not a method is GET by using request.method == 'GET' and request.method == 'POST' for POST.
To access the data inside the method, use request.POST.get("search", None), which basically says find the input with the name attribute from the form or if the input does not exist, return None.
So, all in all, your code should now look like this
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
if request.method == 'GET':
return render(request, 'home/home.html', context={})
# Handles the search once the submit button in the form is pressed
# which sends a "POST" request
if request.method == 'POST':
# Get the input data from the POST request
search_query = request.POST.get('search', None)
# Validate input data
if search_query and search_query != "":
# Implement search functionality....
# ...
return HttpResponse(search_query)
else:
print("Invalid input")
return render(request, 'home/home.html', context={})
Now inside the app, make a folder named templates and add index.html
The index.html file should look like (to learn more about templates refer to: https://docs.djangoproject.com/en/2.2/topics/templates/):
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="POST">
{% csrf_token %}
<input type="text" name="search" placeholder="some text"><br>
<button class="button" name="submit" type="submit">Search</button>
</form>
</body>
</html>
my_app/templates/index.html
Also, if you look at the <form> tag, you can find a method tag which says POST. This indicates whether the data that is being submitted is a POST request.
Befor all :
Djano VERSION = 1.8, and it's obligatory that I use this version
Question
I do not know why I cannot update the User instance by a form.
I mean by updating: changing the value in the database and in the request
The User model is not created by me but I use django.contrib.auth.models.User
Code
This is my code
app/forms.py
from django import forms
from django.contrib.auth.models import User
class ModificationForm(forms.ModelForm):
class Meta:
model = User
fields = ['email']
app/views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from app.forms import ModificationForm
#login_required
def profil(request):
if request.method == "POST":
form = ModificationForm(data=request.POST, instance=request.user)
if form.is_valid():
form.save()
else:
form = ModificationForm()
return render(request, "profil.html", {'form':form})
profile.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Profil</title>
</head>
<body>
<h1>Profil</h1>
<a href='/deconnexion'> Logout </a>
<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Enregistrer" />
</form>
</body>
</html>
Your posting to the wrong link!
If you do not know it, just leave the action empty in the html insted of action="." !
New to Django and to programming.
I want to create a search page and currently have the following.
My urlpatterns has the following as one of it's patterns.
url(r'^search/$', view=search, name='search')
my views has a function
def search(request):
if request.GET.get('q'):
message = 'You submitted: %r' % request.GET['q']
else:
message = 'You submitted nothing!'
return render(request, 'myapp/search.html', {'message': message})
search.html has
<!DOCTYPE html>
<html>
<head>
<title>Search</title>
</head>
<body>
<h1> Search </h1>
<form action="/search/" method="get" >
<input type="text" name = "q">
<input type="submit"value="Search"/>
</form>
</body>
</html>
My issue is when I go to "myapp/search" i see the search box and I see in django debug toolbar that "views.search" function is captured, but when I enter text in the search box and click "search" I receive "The current URL, search/, didn't match any of these." plus the django debug toolbar shows only a GET variable capture, but nothing in Views.
1) So how do I associate 'views.search' after I click the 'search' button.
2) In my url patterns do I need another url pattern, if so what should it be?
Thanks
You said yourself that the URL is "/myapp/search/", but the "action" parameter of your form - which determines where the form data is sent - is just "/search/". You need to make it the same, so that the data is sent to that URL.
The best way to do it is to use the {% url %} tag:
<form action="{% url "search" %}" method="get">
I am lost here. I am quite new to django and maybe this is a newbie question.
I have a very simple list view , which shows the records in the database and a create view to add these objects :
#login_required
def list_view(request):
objects = Foo.objects.all()
ctx = {'objects': objects}
return render_to_response('main/foos.html', ctx,
context_instance=RequestContext(request))
#login_required
def create_view(request):
if request.method == 'POST':
form = FooForm(request.POST)
if form.is_valid():
form.save()
return redirect('/foos/')
else:
form = FooForm()
ctx = {'form': form}
return render_to_response('main/foo_form.html', ctx,
context_instance=RequestContext(request))
The foo_form.html template looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Club</title>
</head>
<body>
<form action="." method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Confirm/>
</form>
</body>
</html>
Url settings:
urlpatterns = patterns('',
url(r'^foos/$', 'list_view'),
url(r'^foos/new$', 'create_view'),
)
When I type the url "localhost:8000/foos/new", the create view gets the GET request as expected. The problem is, upon submitting the form, I am redirected to the list (using a debugger I found out the request is getting to the list_view), even when form action is set to "."
What am I doing wrong? The create_view view should receive the POST request .
Any help is appreciated! Again, I am sorry if this is a newbie question
You haven't finished the regex string in the second url
url(r'^foos/new$', 'create_view')
so "." will use the current url to POST the form. Django takes the url '/foos/new' and matches it against the regex. It matches the first regex, as it finds a match for 'foos', so goes to the 'list_view'. Just finish your regex correctly and it will work.
url(r'^foos/new/$', 'create_view')
Leave the form action as "" to post to the same url rather than having a .
So in this case
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Confirm/>
</form>
Im trying to get a basic app working in Django that incorporates AJAX.
The app will take a domain name and will then send it to the server, which will do a dns lookup on it and then send the response back via AJAX to the client.
Views
from django.http import *
from django.shortcuts import render_to_response
from django.template import RequestContext
import sys
import os
import socket
def main(request):
if request.method == 'POST':
dig_input = request.POST['digInput']
digoutput = socket.gethostbyname(dig_input)
return render_to_response('digajax.html', {'response': digoutput}, context_instance=RequestContext(request))
else:
return render_to_response('digajax.html', context_instance=RequestContext(request))
URLs
url(r'^digajax$', 'digajax.views.main'),
Templates
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.2.js'></script>
<script type="text/javascript">
function send_request(){
$.get(location.href, function(data){
$("#output").html(data.output);
});
}
</head>
<body>
<form method="post" name="diginput form" action="/digajax">
{% csrf_token %}
<input name="digInput" id="digInput" type="text">
<input type="button" onclick="send_request();" value="Request this page with AJAX">lookup</input>
</form>
{% if response %}
<div id="output">
<p>{{ response|linebreaksbr }}</p>
</div>
{% else %}
<p>no</p>
{% endif %}
</body}
</html>
Without AJAX everything is working. Now that I want to use AJAX Im not what what code I should add to each section.
Any help would be really appreciated...............
Django provides an method on the request object your view is passed which will tell you whether the request was made via XmlHttp, request.is_ajax().
If that method returns true, you probably want to return only the fragment of the page you want to update, instead of the whole page.
If that method returns false, you probably want to return the entire page, since the user either has JavaScript turned off, or there was some type of error which caused the view to be requested normally.
So, your view should look like:
def main(request):
if request.method == 'POST':
dig_input = request.POST['digInput']
digoutput = socket.gethostbyname(dig_input)
if request.is_ajax():
return HttpResponse("<p>%s</p>" % digoutput)
else:
return render(request, 'digajax.html', {
'response': digoutput
})
else:
return render(request, 'digajax.html')
Your JavaScript code should be look like:
<script type="text/javascript">
function send_request(){
$.get(location.href, function(data){
$("#output").html(data);
});
}
</script>