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.
Related
I am trying to make a html dropdown and pass the values into Postgrase SQL database. My dropdown values are being retrieved from another database table. It gives me a MultiValueKeyDictError every time I submit the form. I know I can use forms.py to do the same thing but I want to explore the HTML way of doing this.
My HTML file
<form action = "" method = "post">
{% csrf_token %}
<label for = "LogType"></label>
<input id ="LogType" type = "text" value = "{{ user.department }}">
<label for ="DelayCategory">Delay Category</label>
<select id = "delaycategory" class = "form-control">
{%if user.department == 'TechAssembly'%}
{%for techdelay in techdelay%}
<option value = "{{ techdelay.DelayCode }}">{{ techdelay.DelayCategory}}</option>
{%endfor%}
{%endif%}
{%if user.department == 'Testing'%}
{%for testdelay in testdelay%}
<option value = "{{ testdelay.DelayCode }}">{{ testdelay.DelayCategory}}</option>
{%endfor%}
{%endif%}
</select>
<label for = "iterations">Iterations</label>
<input type = "number" id = "iterations">
<center><input type="submit" value=Submit id = "button"></center>
</form>
My Views.py file
def rulesView(request, user_name):
testdelay = TestingDelayCategory.objects.all()
techdelay = TechDelayCategory.objects.all()
if request.method == "POST":
rulesnew = rules()
rulesnew.DelayCategory = request.GET['DelayCategory']
rulesnew.LogType = request.POST('LogType')
rulesnew.iterations = request.POST('iterations')
rulesnew.save()
context = {
'techdelay':techdelay,
'testdelay':testdelay,
}
return render(request, 'rules/rules.html', context)
rulesnew.DelayCategory = request.GET['DelayCategory']
rulesnew.LogType = request.POST('LogType')
rulesnew.iterations = request.POST('iterations')
Have a second look at this: request.GET should be request.POST and request.POST('LogType') should be request.POST['LogType'] same with iterations.
The error message should include the exact line where the errors was raised. So it would have been way easier to debug if you have told us that the error was raised e.g. in this line rulesnew.LogType = request.POST('LogType')
I am trying to get a value out of a SELECT tag.
My HTML is
<div class="form-group">
<label for="acadYear">Academic Year:</label>
<select id="acadYear" name"acadYear">
<option value="2017-18">This Academic Year</option>
<option value="2018-19">Next Academic Year</option>
</select>
</div>
My python code to get this value is
acadYear=self.request.get('acadYear')
This doesn't return anything. When I try
acadYear=self.request.get_all('acadYear')
throws an error
BadValueError: Expected string, got []
What's happening? Any clues?
MORE DETAILS
The Entity
from google.appengine.ext import ndb
class Allocation(ndb.Model):
acadYear = ndb.StringProperty()
branch = ndb.StringProperty()
semester = ndb.StringProperty()
subjectCode = ndb.StringProperty()
subjectName = ndb.StringProperty()
facultyId = ndb.StringProperty()
facultyName = ndb.StringProperty()
choiceNumber = ndb.StringProperty()
status = ndb.StringProperty()
createdOn = ndb.DateTimeProperty(auto_now_add=True)
#classmethod
def faculty_query(cls, parent_key):
return cls.query(ancestor=parent_key).order(-cls.createdOn)
HTML Code to Receive Data
<form action="" method="post">
<legend>Mention Your New Preferences Here</legend>
<div class="form-group">
<label for="acadYear">Academic Year:</label>
<select id="acadYear" name="acadYear">
<option value="2017-18">This Academic Year</option>
<option value="2018-19">Next Academic Year</option>
</select>
</div>
<div class="form-group">
<label for="branch">Branch:</label>
<input type="text" id="branch" name"branch" value="CSE or ISE or MCA">
</div>
<div class="form-group">
<label for="semester">Semester:</label>
<input type="text" id="semester" name="semester" value="From 1 to 8"/>
</div>
<div class="form-group">
<label for="choiceNumber">Choice#:</label>
<input type="text" id="choiceNumber" name="choiceNumber" value="1,2,3"/>
</div>
<div class="form-group">
<label for="subjectCode">Subject Code:</label>
<input type="text" id="subjectCode" name="subjectCode" value="Example: 10CS43"/>
</div>
<div class="form-group">
<label for="subjectName">Subject Name:</label>
<input type="text" id="subjectName" name="subjectName" value="Example: Design and Analysis of Algorithms"/>
</div>
<div class="form-group">
<button type="submit">Save Preference</button>
</div>
</form>
Python Handler
MainHandler Class
class MainHandler(webapp2.RequestHandler):
def _render_template(self, template_name, context=None):
if context is None:
context = {}
# Get the logged in user
user = users.get_current_user()
ancestor_key = ndb.Key("User", user.nickname())
qry = Allocation.faculty_query(ancestor_key)
context['allocs'] = qry.fetch()
template = jinja_env.get_template(template_name)
return template.render(context)
#ndb.transactional
def _create_alloc(self, user):
alloc = Allocation(parent=ndb.Key("User", user.nickname()),
acadYear=self.request.get_all('acadYear'),
branch=self.request.get('branch'),
semester=self.request.get('semester'),
subjectCode=self.request.get('subjectCode'),
subjectName=self.request.get('subjectName'),
facultyId=user.user_id(),
facultyName=user.nickname(),
choiceNumber=self.request.get('choiceNumber'),
status='Requested')
alloc.put()
def get(self):
user = users.get_current_user()
if user is not None:
logout_url = users.create_logout_url(self.request.uri)
template_context = {
'user': user.nickname(),
'logout_url': logout_url,
}
self.response.out.write(
self._render_template('main.html', template_context))
else:
login_url = users.create_login_url(self.request.uri)
self.redirect(login_url)
def post(self):
user = users.get_current_user()
if user is None:
self.error(401)
self._create_alloc(user)
logout_url = users.create_logout_url(self.request.uri)
template_context = {
'user': user.nickname(),
'logout_url': logout_url,
}
self.response.out.write(
self._render_template('main.html', template_context))
acadYear=self.request.get_all('acadYear') returns a list - apparently in Unicode - which need to become string for putting into data store.
I have tried the following
(1) Use an intermediate variable = does not work.
(2) Encoding to UTF-8 - can't because the list does not have an encode method.
(3) I don't know which element would be chosen [0] or [1]. Hence I can't try
acadYear=self.request.get_all('acadYear')[0].encode('UTF-8').
Such a simple thing - but - why it had to be so complex!
Any help is appreciated. I am losing face before kids.
You have a typo in this line:
<select id="acadYear" name"acadYear">
You need to add an "=" after "name". Because of this typo, your browser is not sending the data for the select field.
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))
I'm a learner in Python and Django.
I am trying to pass selected checkboxes to my views and then make a get() call to fetch related objects, but keep getting the error DoesNotExist, even though the object is present in the database.
I tried changing the get() parameters but it still shows the same error, as if it just cannot fetch the database. Please help!
ERROR IS IN THE #ed LINE
Here is my views.py
def manage(request):
if request.POST.get('taskname'):
name = request.POST.get('taskname')
end = request.POST.get('enddate')
emp = User.objects.get(username = request.user.username)
print emp.username
try:
newtask = Task(taskname = name, deadline = end, status = 'incomplete', empid = emp)
newtask.save()
except:
print "not saved"
my_tasks = Task.objects.filter(empid = emp)
return render(request, 'ellipse/dashboard.html', {'employee': emp, 'tasks': my_tasks})
else:
selected = request.POST.get('dropdown')
if selected == 'Delete':
tasks = request.POST.getlist('t')
emp = User.objects.get(username = request.user.username)
for seltask in tasks:
#deltask = Task.objects.get(taskname=seltask)
deltask.delete()
my_tasks = Task.objects.filter(empid = emp)
return render(request, 'ellipse/dashboard.html', {'employee': emp, 'tasks': my_tasks})
And, my html:
<div>
<form action="/ellipse/manage/" method="post">
{% csrf_token %}
<p>Taskname <input type="text" name="taskname"></p>
<p>Deadline <input type="date" name="enddate"></p>
<select name="dropdown">
<option selected="selected" disabled>Select action :</option>
<option value="Add">Add</option>
<option value="Delete">Delete</option>
<option value="Mark as complete">Mark as complete</option>
<option value="Mark as incomplete">Mark as incomplete</option>
</select>
{% if tasks %}
{% for tasko in tasks %}
<p><tr><td><input type="checkbox" name="t" value={{ tasko.taskname }}/></td><td>{{ tasko.taskname }}</td><td>{{ tasko.deadline }}</td><td>{{ tasko.status }}</td></tr></p>
{% endfor %}
{% endif %}
<p><button type="submit" name="modify">Modify</button></p>
</form>
</div>
I am clueless on how to proceed further and it'd be great help if this issue can be resolved. Thanks in advance!
Well your get looks jacked up.
emp = User.objects.get(username = request.user.username)
should probably be something like this.
emp = User.objects.get(id=request.user.id)
You could probably do this to...
emp = User.objects.get(user=request.user)
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))