How do I pass url parameter to form value? - python

The form has this hidden field
<input type="hidden" name="dir_type" value="tshirt">
url parameters are
/dir?type=tshirt
/dir?type=books
/dir?type=posters
and so on.
Now I hard coded value="tshirts" but how do I get parameter for the relevant page?
I found several pages like this dealing with similar topics but I did not understand how this is done.
Thanks for your help.
UPDATE
The answer by systempuntoout works perfectly but I decided to solve the problem without using templates. And for anyone who has a similar question, passing the url parameter to the form like this works well:
<form name="submit_form" action="/directorysubmithandler" method="post" onSubmit="return validate_form()">
title: <input type="text" name="title" size=50><br />
url: <input type="text" name="url" size=50><br />
<input type="hidden" name="dir_type" value="%s")>
<input type="submit" value="submit">
</form>""" % self.request.get("type"))

a. pass the type value to the view:
class Directory(webapp.RequestHandler):
def get(self):
....
merchandise_type = self.request.get("type", "")
items = Item.all()
items.filter("type =", merchandise_type)
path = os.path.join(os.path.dirname(__file__), 'dir_details.html')
self.response.out.write(template.render(path,{'type':merchandise_type}))
b. add the type value to the hidden field:
<input type="hidden" name="dir_type" value="{{ type }}">
c. get the dir_type value in your post handler:
class DirectorySubmitHandler(webapp.RequestHandler):
def post(self):
user = users.get_current_user()
merchandise_type = self.request.get("dir_type", "")
dir_type = merchandise_type
if user:
item = Item()
item.title = self.request.get("title")
item.url = self.request.get("url")
item.type = self.request.get("dir_type")
item.user_who_liked_this_item = user
item.put()
self.redirect("/dir?type=%s" %
self.request.get("dir_type"))
else:
self.redirect(users.create_login_url(self.request.uri))

Related

Button to save data from a result to a data table; user token required error

I'm trying to add a button that takes data from a search results page and adds it to a data table. For example the first search result displays properly and I want the Favorites Button to save the data for the logged in user.
I keep getting the "message": "Token is Missing!" from the helper.py.
Fairly new to all this so I know I'm not using the best methods but at this point would just like to get this to work somewhat.
I'm guessing this is due to the #token_required. But I'm not sure how to fix this.
This is the route.
#api.route('/movies', methods = ['POST'])
#token_required
def save_movie(current_user_token):
title = request.json['title']
tmdb_id = request.json['tmdb_id']
user_token = current_user_token.token
print(f"User Token: {current_user_token.token}")
movie = SaveMovie(title, tmdb_id, user_token=user_token)
db.session.add(movie)
db.session.commit()
response = movie_schema.dump(movie)
return jsonify(response)
and this is the form I'm using
<form action="/api/movies" method="POST">
<input type="hidden" name="title" value="{{ results.0.title }}"/>
<input type="hidden" name="tmdb_id" value="{{ results.0.id }}"/>
<input type="hidden" name="x-access-token" value="Bearer {{ current_user.token }}"/>
<button name ="submit" class="btn btn-primary" type="submit">Favorite</button>
</form>
This is the Model
class Movie:
"""
Movie class to define Movie Objects
"""
def __init__(self,id,title,overview,poster):
self.id = id
self.title = title
self.overview = overview
self.poster = f"https://image.tmdb.org/t/p/w500/{poster}"
And these are the functions
def search_movie(query):
data = requests.get(f"{BASEURL}/search/movie?api_key={API_KEY}&language=en-US&query={query}&page=1&include_adult=false").json()
if data['results']:
search_data = process_results(data['results'])
return search_data
def process_results(movie_list):
movie_results = []
for movie_item in movie_list:
id = movie_item.get('id')
title = movie_item.get('original_title')
overview = movie_item.get('overview')
poster = movie_item.get('poster_path')
if poster:
movie_object = Movie(id, title, overview, poster)
movie_results.append(movie_object)
return movie_results
I've attempted to add the token in the form to see if that would help but that didn't work and I'm not sure if maybe I need a #login-required for the search results but that would not be ideal. Would creating another function as a go between fix this?

Date not rendering in Django template

I am attempting to pass date values from views.py (passed in from managers.py), but they are not rendering in my template.
I made sure that the date value is correct by printing it to the console and adding it to my template. It renders fine without any filters, but when I used the exact same syntax from earlier in my project—where it worked—all I get are blank values.
managers.py
tz = pytz.timezone('America/Chicago')
class ProfileManager(Manager):
def index(self, request):
profile = models.Profile.objects.get(user__pk=request.session['id']) \
if 'id' in request.session else None
appts = []
next_appt = None
if profile != None:
try:
next_appt = Appointment.objects.get(
profile=profile,
date_end__gt=datetime.now(pytz.utc),
)
except Appointment.DoesNotExist:
next_appt = None
except MultipleObjectsReturned:
next_appt = Appointment.objects.filter(
profile=profile,
date_end__gt=datetime.now(pytz.utc),
).first()
appts = Appointment.objects \
.filter(date_end__gt=datetime.now(pytz.utc)) \
.exclude(profile__user=None)
return {
'profile': profile,
'next_appt': next_appt,
'appts': appts,
'TIME_ZONE': TIME_ZONE,
'current_date': datetime.now(tz),
}
views.py
def index(request):
response = Profile.objects.index(request)
return render(request, 'users/index.html', response)
index.html
<div id="datePickerDate">
{{ current_date }}
<input type="hidden" name="year" value="{{ current_date|date:'Y' }}" autocomplete="off">
<input type="hidden" name="month" value="{{ current_date|date:'n' }}" autocomplete="off">
</div>
Result
<div id="datePickerDate">
Aug. 19, 2019, 4:27 p.m.
<input name="year" value="" autocomplete="off" type="hidden">
<input name="month" value="" autocomplete="off" type="hidden">
</div>
I can't think of what I'm missing. Any help is appreciated.
I found that the issue was in my JavaScript. I was adding values to the input fields though jQuery without realizing it, and those values were undefined. It appears I should be more cognizant of what code I actually need when I copy and paste code from other parts of a project, or any other source for that matter.

How to filter price range for products in django?

I am trying to filter my products list by price specified by user(min and max price).I have two input box for taking price range.'price' is one of the column in my database table.I am getting error as int() argument must be a string or a number, not 'dict'.I have include my template file and small part of views file.
Models.py,
class Add_prod(models.Model):
book = models.CharField("Book Name",max_length=40)
author = models.CharField("Author",max_length=30)
price = models.PositiveIntegerField("Price")
image = models.ImageField(upload_to='images',null=True)
cat = models.ForeignKey(Add_cat,on_delete=models.PROTECT)
def __unicode__(self):
return "%s" % (self.cat)
My template file,
<p>Price</p>
<input type="text" name="min_price" maxlength="4" size="3" >
to <input type="text" name="max_price" maxlength="4" size="3">
<input type="submit" value="Go">
views.py,
#csrf_protect
def welcome_user(request):
if 'min_price' in request.GET:
filter_price1 = request.GET.get('min_price')
filter_price2 = request.GET.get('max_price')
if filter_price1 =='':
filter_price1=0
if filter_price2=='':
filter_price2=Add_prod.objects.all().aggregate(Max('price'))
my_products = Add_prod.objects.filter(price__range=(filter_price1,filter_price2))
context = { "products":my_products}
return render(request,"welcome-user.html",context)
I also tried like this,
my_products = Add_prod.objects.raw('SELECT * FROM books_add_prod where price between filter_price1 and filter_price2')
Maybe this line wrong filter_price2=Add_prod.objects.all().aggregate(Max('price'))
Cause aggragate will return a dict
See this docs Aggragation
Try this:
my_products=Add_prod.objects.filter(price__range(filter_price1,filter_price2['price_max']))
Use aggregation (cheatsheet) as follows to determine the maximum price:
from decimal import Decimal as D
...
price1 = D(request.GET.get('min_price', 0))
price2 = D(request.GET.get('max_price', 0))
if not price2:
price2 = Add_prod.objects.aggregate(Max('price'))['price__max']
my_products = Add_prod.objects.filter(price__range=(price1, price2))
On a different note, why do you use text inputs for price which I assume is a DecimalField? What about a number input (or a django form) in order to make sure that the casts in your view don't raise errors :
<input type="number" name="min_price" min="0" step="0.01" >
Here is what worked for me, this might not be the optimal way to do it. But it works so anyone from future could give it a try:
<form method="get">
<input type="text" name="min_price" maxlength="4" size="3" required>
to <input type="text" name="max_price" maxlength="4" size="3" required>
<input type="submit" value="Go">
</form>
And In your Views:
if 'min_price' in request.GET:
filter_price1 = request.GET.get('min_price')
filter_price2 = request.GET.get('max_price')
if filter_price1 =='':
filter_price1=0
products = Products.objects.filter(price__range=(filter_price1,filter_price2))

POST.has_key method error

When I don't fill out anythin in 'Title', I expect It shows me the message 'Fill out title. But It just shows me blank..
views.py
def add_post(request):
entry_title = request.POST.get("title", False)
if request.POST.has_key('title') == False:
return HttpResponse('Fill out title')
else:
return HttpResponse('Hello %s' % entry_title)
write.html
<form method="post" action="/blog/add/post/">{% csrf_token %}
<p>
<label for "title">Title</label>
<input type="text" id="title" name="title" value="" />
</p>
</form>
Firstly, foo.has_key('bar') should be spelled 'bar' in foo.
Secondly, all you're doing is checking if there is a field called title in the form. Well, yes, of course there is, because you put it there yourself. What you should be checking is if that field has any actual content.
if not entry_title:
return HttpResponse('Fill out title')

NameError - global name not defined

I am trying to read some data from html forms and insert it into database. Doing so i am stuck with this error "NameError at /createEmployee/ : global name 'get_post_param' is not defined" ; i will paste my code here. Can somebody help me to solve this.
VIEWS.PY
def createEmployee(request):
if request.method == "POST":
userName = get_post_param(request,"userName")
designation = get_post_param(request,"designation")
employeeID = get_post_param(request,"employeeID")
contactNumber = get_post_param(request,"contactNumber")
project = get_post_param(request,"project")
dateOfJoin = get_post_param(request,"dateOfJoin")
EmployeeDetails(userName=userName,designation=designation,employeeID=employeeID,contactNumber=contactNumber,project=project,dateOfJoin=dateOfJoin).save()
return render_to_response('createEmployee.html')
else:
return render_to_response('createEmployee.html')
TEMPLATE.PY
<form action="http://127.0.0.1:8000/createEmployee/" method="POST">
Name: <input type="text" name="userName" /><br />
Designation: <input type="text" name="designation" /><br>
EmployeeID: <input type="text" name="employeeID" /><br>
Contact Number: <input type="text" name="contactNumber" /><br>
Project: <input type="text" name="project" /><br>
Date Of Join: <input type="text" name="dateOfJoin" /><br>
<input type="submit" value="Submit" /><br />
</form>
This is a very simple problem. You have not defined get_post_param.
Where did you get this get_post_param idea?
Simply define a function called get_post_param to fix it..
Here's a python shell session
>>> get_post_param(request, 'userName')
NameError: not defined
>>> def get_post_param(request, param):
... return request.POST.get(param)
# or scrap the idea of a function to do a one liner op anyways
>>> get_post_param(request, 'userName'):
'my_username'

Categories

Resources