I'm using Python Pyramid with Jinja2 template. I want to save my form data into session and retrieve it in another HTML page. How should I change in order to pass the data? I only know how to store the data I key in Views.py into session like this request.session['postal'] = 01934 but this is not the data I key in Delivery.jinja2. And if I used print (session['postal']), this will only show in my command prompt but not HTML page. Can anyone help me out? I'm a beginner to this.
What to add in/ change in my Views.py?
my HTML: Delivery.jinja2
<form class="form-horizontal" method="POST">
<div class="form-group">
<label class="control-label col-md-2" for="postal">Postal Code:</label>
<input type="text" class="form-control" id="postal" placeholder="Enter Postal Code" name="postal" />
</div>
<div class="form-group">
<label class="control-label col-md-2" for="address">Detailed Address:</label>
<textarea class="form-control" rows="3" id="address" placeholder="Enter Address" name="address"></textarea>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="unit">Unit No #:</label>
<input type="text" class="form-control" id="unit" placeholder="Enter Unit No" name="unit" />
</div>
<button type="submit" class="btn btn-default" name="submit">Submit</button>
</form>
Views.py
#view_config(route_name='deliveryLink', renderer='templates/deliveryLink.jinja2')
def deliveryLink(request):
print("YAY for gift delivery via Link")
if 'submit_deliverylink' in request.POST:
print("request.POST: ", request.POST)
myform = request.POST
for m in myform:
print("key: ", m, " value: ", myform[m])
session = request.session
session['postal'] = ?
session['address'] = ?
session['unit'] = ?
data = "??"
data_array = data.split(",")
session['data'] = data_array
session['delivery'] = str(data_array)
print (session['delivery'])
return HTTPFound(location='http://localhost:5555/confirmation')
return {}
#view_config(route_name='confirmation', renderer='templates/confirmation.jinja2')
def confirmation(request):
print("YAY for confirmation")
for a in request.POST:
request.session[a] = request.POST[a]
return {}
and I want the data entered previously to show on this confirmation page: Confirmation.jinja2
<form class="form-horizontal" method="POST">
<div class="form-group">
<label class="control-label col-md-2" for="postal">Postal Code:</label>
<input type="text" class="form-control" id="postal" name="postal" />
</div>
<div class="form-group">
<label class="control-label col-md-2" for="address">Detailed Address:</label>
<textarea class="form-control" rows="3" id="address" name="address"></textarea>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="unit">Unit No #:</label>
<input type="text" class="form-control" id="unit" name="unit" />
</div>
</form>
I think, you can just pass POST from initial form to template of confirmation page, without session.
If anyway you need session, you can call it from your template
<input type="text" class="form-control" id="postal" name="postal" value="{{session['postal']}}" />
# after form submitted, it sends post request, just check if it exist
if request.POST:
print("request.POST: ", request.POST)
myform = request.POST
# you need iterate over keys for this case
for m in myform.keys():
print("key: ", m, " value: ", myform[m])
session = request.session
# you can access request.POST directly or use your variable myfrom
# use myform.get('postal','') to get value by key
session['postal'] = myform.get('postal','')
session['address'] = myform.get('postal','')
session['unit'] = myform.get('unit','')
data = "??"
data_array = data.split(",")
session['data'] = data_array
session['delivery'] = str(data_array)
print (session['delivery'])
return HTTPFound(location='http://localhost:5555/confirmation')
Related
I have 5 radio buttons and each have different values but as user can only select 1 option out of 5 and after selecting the value of radio button should be stored in my django models.
This is my html code
<div class="col">
<div class="form-group">
<input class="form-check-input" type="radio" name="reason" id="reason1" checked>
<label class="form-check-label" for="reason1">
Casual Leave
</label>
</div>
<div class="form-group">
<input class="form-check-input" type="radio" name="reason" id="reason2">
<label class="form-check-label" for="reason2">
Medical Leave
</label>
</div>
<div class="form-group">
<input class="form-check-input" type="radio" name="reason" id="reason3">
<label class="form-check-label" for="reason3">
Earned Leave
</label>
</div>
<div class="form-group">
<input class="form-check-input" type="radio" name="reason" id="reason4">
<label class="form-check-label" for="reason4">
Office Duty
</label>
</div>
<div class="form-group">
<input class="form-check-input" type="radio" name="reason" id="reason5">
<label class="form-check-label" for="reason5">
Compensatory Off
</label>
</div>
</div>
*this code contains form tag
My Django function
def leaveapplicationsubmit(request):
if request.method == 'POST':
reason1 = request.POST['reason1']
reason2 = request.POST['reason2']
reason3 = request.POST['reason3']
reason4 = request.POST['reason4']
reason5 = request.POST['reason5']
if 'reason1' in request.POST:
reason = "Casual Leave"
elif 'reason2' in request.POST:
reason="Medical Leave"
elif 'reason3' in request.POST:
reason="Earned Leave"
elif 'reason4' in request.POST:
reason="Office Duty"
elif 'reason5' in request.POST:
reason="Compensatory Off"
else:
return HttpResponse('Please select the reason')
else:
return HttpResponse("Failed")
Please help me with it, I really need that
All of the buttons have name="reason". That is the name you should look for in the code, not reason1, reason2 etc. Those are ids, not names.
Also, each button needs a value attribute, so you can tell which one was pressed.
Look at the examples here https://www.w3schools.com/tags/att_input_type_radio.asp
In views write this code, here reason_ will hold the value which will be selected by the user and in HTML code write it as given here https://www.w3schools.com/tags/att_input_type_radio.asp then reason_ will hold the value of the selected option
def radio(request):
if request.method == "POST":
d = request.POST
for key,value in d.items():
if key == "reason":
reason_ = value
I am trying to retrieve data from a form using the Post method and store it in the database. However, when I click on the submit button,I keep on getting the following error:
NOT NULL constraint failed: posts_subscribe.firstname
Here is my views.py:
def subscribe(request):
if request.method == 'POST':
firstname=request.POST.get('firstname')
secondname=request.POST.get('secondname')
email=request.POST.get('email')
phonenumber=request.POST.get('phonenumber')
en= Subscribe(firstname=firstname, secondname=secondname, email = email, phonenumber = phonenumber)
en.save()
return redirect('/')
return render(request, 'subscribe.html')
My models.py:
class Subscribe(models.Model):
firstname = models.CharField(max_length=30, blank = True)
secondname = models.CharField(max_length=30, blank = True)
email = models.CharField(max_length=30)
phonenumber = models.IntegerField()
Here is my template:
{% extends 'index.html' %}
{% block subscribe %}
<div class="card mx-5">
<h1 class="mx-5 mt-3"> Subscribe</h1>
<form method="POST" enctype="multipart/form-data" action="subscribe">
{% csrf_token %}
<div class="mb-3 mx-5">
<label for="firstname" class="form-label ">First Name</label>
<input type="text" class="form-control form-control-lg" id="firstname" placeholder="firstname">
</div>
<div class="mb-3 mx-5">
<label for="secondname" class="form-label">Second Name (Optional)</label>
<input type="text" class="form-control form-control-lg" id="secondname" placeholder="secondname">
</div>
<div class="mb-3 mx-5">
<label for="email" class="form-label">Email</label>
<input type="email" class="form-control form-control-lg" id="email" placeholder="example#example.com">
</div>
<div class="mb-3 mx-5">
<label for="phonenumber" class="form-label">Phonenumber</label>
<input type="number" class="form-control form-control-lg" id="phonenumber" placeholder="0712345678">
</div>
<div class="mb-3 mx-5">
<button type="submit" class="btn-primary"> Subscribe</button>
</div>
</form>
</div>
{% endblock %}
And my url patterns:
urlpatterns= [
path('', views.index, name='index'),
path('subscribe', views.subscribe, name ='subscribe'),
path('allposts', views.allposts, name='allposts'),
path('political', views.political, name='political'),
path('religion', views.religion, name='religion'),
path('trending', views.trending, name='treniding'),
path('<str:pk>', views.post, name='post'),
]
You should add a name="…" attribute [mdn] to the <input> elements, so:
<input type="text" name="firstname" class="form-control form-control-lg" id="firstname" placeholder="firstname">
…
<input type="text" name="secondname" class="form-control form-control-lg" id="secondname" placeholder="secondname">
…
<input type="email" name="email" class="form-control form-control-lg" id="email" placeholder="example#example.com">
…
<input type="number" name="phonenumber" class="form-control form-control-lg" id="phonenumber" placeholder="0712345678">
so no matter what I seem to do I can't get a valid form from just a integer field.
Controller:
def upload_image(request):
if request.method == "POST":
form = AddFloorplan(request.POST, request.FILES)
print request.POST.get('floornumber')
if form.is_valid():
print 'valid'
else:
print(form.errors)
return redirect("/wayfinder/editor/")
Form:
class AddFloorplan(forms.Form):
floor_number = forms.IntegerField(required=True)
Template:
<form action="/wayfinder/addfloorplan/" method="POST" enctype="multipart/form-data"> {% csrf_token %}
<div class="input-field col s12">
<input id="floornumber" autofocus name="floornumber" placeholder="Floor Number" type="text" required>
</div>
<div class="col s12">
<p>
<button class="btn waves-effect waves-light z-depth-0" type="submit" name="action">
<span>Upload</span>
</button>
</p>
</div>
</form>
had no luck passing the values
The name of your form field, floor_number
floor_number = forms.IntegerField(required=True)
does not match the name of your form input, floornumber
<input id="floornumber" autofocus name="floornumber" placeholder="Floor Number" type="text" required>
You need to use the same name in both places.
I have this html search form and I want to link it to my search view to make it work.
<form class="navbar-form navbar-left" role="search" >
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" action = "/search/">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
Here is the views.
def searchResults(request, drname):
# drname = request.GET.get('drname')
doctors = Doctor.objects.filter(name__contains=drname)
clinic = Doctor.objects.filter(clinic__name__contains=drname)
d = getVariables(request)
d['doctors'] = doctors
d['doctors_by_clinic'] = doctors
return render_to_response('meddy1/doclistings.html',d)
urls.py
url(r'^search/(?P<drname>\w+)/$', views.searchResults, name='searchResults'),
Html. <form> must have action attribute, not <input>. Also, send search string as get parameter, don't include it in url (add name attribute to <input>):
<form class="navbar-form navbar-left" role="search" action="/search/">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" name="drname">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
urls.py. Drop this part (?P<drname>\w+)/:
url(r'^search/$', views.searchResults, name='searchResults'),
views.py. Get search string from GET parameter:
def searchResults(request):
drname = request.GET.get('drname')
doctors = Doctor.objects.filter(name__contains=drname)
clinic = Doctor.objects.filter(clinic__name__contains=drname)
d = getVariables(request)
d['doctors'] = doctors
d['doctors_by_clinic'] = doctors
return render_to_response('meddy1/doclistings.html',d)
action goes in the form element, not the input.
i have code for form , i want to save the data through a form.
custom form is :-
<form class="well span12 c1" name="contacts" method="POST">
<label>First Name</label>
<input type="text" placeholder="Your First Name" class="span12" required name="firstname" >
<label>Last Name</label>
<input type="text" placeholder="Your Last Name" class="span12" required name="lastname" >
<label>Email Address</label>
<input type="text" placeholder="Your email address" class="span12" required name="email" >
<label>Subject</label>
<select class="span12" name="subject" id="subject" required >
<option value="na" selected="">Choose One:</option>
<option value="service">General Customer Service</option>
<option value="suggestions">Suggestions</option>
<option value="product">Product Support</option>
</select>
<label>Message</label>
<textarea rows="8" class="input-xlarge span12" id="message" name="message" required ></textarea>
<button class="btn btn-primary pull-right" style="border-radius:0px;" type="submit">Send</button>
</form>
views.py :-
#app.route('/contact' , methods = ['GET' , 'POST' ])
def contact():
if request.method == 'POST':
user = user_email(firstname = request.form['firstname'] ,
lastname = request.form['lastname'],
email = request.form['email'],
subject = request.form['subject'],
message = request.form['message'])
user.save()
return render_template('index.html')
else:
return render_template('contact.html')
there is an error of AttributeError: 'Database' object has no attribute 'model'. Please help me to solve this problem.
Have you setup a database, and connected to it? It should look something like this:
# define a database connection
database = peewee.SqliteDatabase('my.db')
class BaseModel(peewee.Model):
class Meta:
# this is likely the missing part of your model
# you need to tell the model which database connection to use.
database = database
class User(BaseModel):
first_name = peewee.CharField()
last_name = peewee.CharField()
email = peewee.CharField()
subject = peewee.CharField()
message = peewee.CharField()
<form class="well span12 c1" name="contacts" method="POST" action="{{ url_for('contact') }}">
<div class="row-fluid">
<div class="span6">
<label>First Name</label>
<input type="text" placeholder="Your First Name" class="span12" required name="firstname" >
<label>Last Name</label>
<input type="text" placeholder="Your Last Name" class="span12" required name="lastname" >
<label>Email Address</label>
<input type="text" placeholder="Your email address" class="span12" required name="email" >
<label>Subject</label>
<select class="span12" name="subject" id="subject" required >
<option value="na" selected="">Choose One:</option>
<option value="service">General Customer Service</option>
<option value="suggestions">Suggestions</option>
<option value="product">Product Support</option>
</select>
</div>
<div class="span6">
<label>Message</label>
<textarea rows="8" class="input-xlarge span12" id="message" name="message" required ></textarea>
</div>
<button class="btn btn-primary pull-right" style="border-radius:0px;" type="submit">Send</button>
</div>
</form>