I want users to be able to query my database via several different parameters (name, year, etc), dynamically add more fields, and join them with boolean operators; the net result would be something like "year = 1900 AND name = chicken AND location = San Francisco." I think I'm doing something wrong, since it's not returning anything, even when I try just one field with a value that I know matches some data (e.g., I can get objects back when I use .filter() from the Django shell). Anyone know how I can fix it?
Relevant view (ignore the sloppy indentation, I didn't want to go through and fix all of it, but it's right in my actual code):
class BaseSearchFormSet(BaseFormSet):
def clean(self):
if any(self.errors):
return self.errors
queries = []
valid_courses = ["appetizer","main","dessert"]
valid_period = re.compile(r'\d\d\d0-\d\d\d5|\d\d\d5-\d\d\d0')
valid_year = re.compile(r'\d{4}')
multi_rows = ["year","period","course"]
for x in xrange(0,self.total_form_count()):
form = self.forms[x]
query = form.cleaned_data.get("query")
row = form.cleaned_data.get("row")
if query in queries and row not in multi_rows:
raise forms.ValidationError("You're already searching for %s.")
queries.append(query)
if row == "course" and query.lower() not in valid_courses:
raise forms.ValidationError("%s is not a valid course option."%(form.cleaned_data["query"]))
if row == "period" and not re.match(valid_period,query):
raise forms.ValidationError("%s is not a properly formatted period. Valid five-year periods span either the first or second half of a decade. For example: 1910-1915, 1925-1930."%(form.cleaned_data["query"]))
if row == "year" and not re.match(valid_year,query):
raise forms.ValidationError("Please enter a four-digit year.")
def search(request):
errors = []
searchFormSet = formset_factory(F.SearchForm, extra=1,formset=BaseSearchFormSet)
if request.GET:
formset = searchFormSet(request.GET)
forms = []
if formset.is_valid():
for x in xrange(0,formset.total_form_count()):
form = {}
form["row"]= formset[x].cleaned_data.get("row",None)
form["query"] = formset[x].cleaned_data.get("query",None)
form["bools"] = formset[x].cleaned_data.get("bools",None)
if form["query"]:
q = form["query"]
else:
errors.append("no query found")
if form["row"]:
row = form["row"]
else:
errors.append("no row found")
filter_keys = {"dish_name":Q(dish__name__icontains=q),
"regex":Q(dish__full_name__regex=r'%s'%(q)),
"course":Q(dish__classification=q.lower()),
"year":Q(page__menu_id__year__exact=q),
"period":Q(page__menu_id__period__exact=q),
"location":Q(page__menu_id__location__icontains=q),
"restaurant":Q(page__menu_id__restaurant__icontains=q)}
forms.append(form)
final_query=Q()
def var_reduce(op,slice):
if op == "and":
return reduce(lambda x,y: x & y,slice)
elif op == "or":
return reduce(lambda x,y: x | y,slice)
for x in xrange(len(forms)):
try:
try:
if final_query:
slice = [final_query,filter_keys[forms[x]["row"]],filter_keys[forms[x+1]["row"]]]
else:
slice = [filter_keys[forms[x]["row"]],filter_keys[forms[x+1]["row"]]]
final_query = var_reduce(forms[x]["bools"],slice)
except IndexError:
if final_query:
slice = [final_query,filter_keys[forms[x]["row"]]]
else:
slice = [filter_keys[forms[x]["row"]]]
final_query = var_reduce(forms[x]["bools"],slice)
items = MenuItem.objects.filter(final_query)
return render_to_response("search_results.html",{"items":items,"formset":formset})
except KeyError as e:
errors.append(e)
formset = searchFormSet(None)
return render_to_response("search_page.html",{"errors":errors,"formset":formset})
else:
formset = searchFormSet(None)
return render_to_response("search_page.html",{"errors":errors,"formset":formset})
else:
formset = searchFormSet(None)
return render_to_response("search_page.html",{"formset":formset})
models:
from django.db import models
class MenuItem(models.Model):
def format_price(self):
return "${0:0<4,.2f}".format(float(self.price))
def __unicode__(self):
return self.dish
dish=models.OneToOneField('Dish',to_field='mk')
price=models.CharField(max_length=5,blank=True)
page=models.OneToOneField('MenuPage')
mk=models.CharField(max_length=10,unique=True)
formatted_price = property(format_price)
class Menu(models.Model):
def period(self):#adapted from http://stackoverflow.com/questions/2272149/round-to-5or-other-number-in-python
try:
p=int(10*round(float(int(self.year))/10))
if p < self.year:
return "%s-%s"%(p,p+5)
else:
return "%s-%s"%(p-5,p)
except (ValueError,TypeError):
return ""
def __unicode__(self):
if self.restaurant:
return self.restaurant
else:
return self.mk
restaurant=models.TextField(unique=False,blank=True,null=True)
year=models.CharField(max_length=4,unique=False,blank=True,null=True)
location=models.TextField(unique=False,blank=True,null=True)
status=models.CharField(unique=False,max_length=20)
mk=models.CharField(max_length=8,unique=True,primary_key=True)
period=property(period)
language = models.CharField(unique=False,max_length=30)
#objects=MenuManager()
class MenuPage(models.Model):
mk=models.CharField(max_length=10,unique=True)
menu_id=models.OneToOneField("Menu",to_field='mk')
#objects=MenuPageManager()
class Dish(models.Model):
def __unicode__(self):
return self.name
full_name = models.TextField()
name=models.CharField(unique=True,max_length=255)
mk=models.CharField(max_length=10,unique=True)
class Classification(models.Model):
def __unicode__(self):
if self.classification:
return self.classification
else:
return "none"
dish=models.OneToOneField('dish',to_field='name')
classification=models.CharField(unique=False,max_length=9)
mk=models.CharField(max_length=10,primary_key=True)
html of my search page:
{% extends "base.html" %}
{% block style %}
<link rel="stylesheet" type="text/css" href="/static/search_style.css" />
{% endblock %}
{% block java %}
<script type="text/javascript" src="/static/searches.js"></script>
{% endblock %}
{% block title %}Search{% endblock %}
{% block head %}Search{% endblock %}
{% block content %}
{% autoescape off %}
<div id="searches">
<form id="search" action="" method="get">
<table border="0" cellpadding="0" cellspace="0">
<tbody class="search">
{% for form in formset.forms %}
<tr>
<td class="row">{{ form.row }}</td>
<td class="query">{{ form.query }}</td>
<td class="bool">{{ form.bools }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{{ formset.management_form }}
<input type="submit" value="Submit" id="submit">
</form>
</div>
{% if formset.errors or errors %}
<div id="errors">
<h3>The following errors were encountered while trying to submit your search:</h3>
{% for x,y in formset.errors.items %}
<p>{{ x }} : {{ y }}</p>
{% endfor %}
{{ errors }}
</div>
{% endif %}
<div id="notes">
<p>Searching by dish names, locations, and restaurants is case-insensitive.</p>
<p>Searching by course uses case-insensitive exact matching. Valid courses are Appetizer, Main, and Dessert.</p>
<p>Years should be entered YYYY. Five-year periods span either the first or second half of a decade, and should be entered YYYY-YYYY. Example valid five-year periods are 1900-1905, 1995-2000, etc.</p>
<p>Regular expression search follows MySQL regular expression syntax, as described here.</p>
</div>
{% endautoescape %}
<br /><br /><br /><br /> <br /><br /><br />
{% endblock %}
{% block footer %}
<div id="warning">
<p>NOTE: This site and the information it contains are still in development. Some information may be missing or inaccurate.</p>
</div>
<div class="credits">
Created and maintained by Sam Raker and Rachel Rakov
<br />
Data graciously provided by What's on the Menu?
</div>
{% endblock %}
Sorry, my original post was more than you needed. To clarify, all you should need to do is:
Q(year__icontains=year_input_variable) | Q(city__icontains=city_input_variable) & Q(name__icontains=name_input_variable)
Use & for and, | for or.
What I had posted earlier is for if a query contains multiple words, it would either check to see if all of the words matched using operator.and or if any of the words matched using operator.or.
Related
I currently am trying to compare two strings with an ifequal tag in Django. The current issue is that although the two strings are equal, Django does not run everything inside the if statement.
html
{% for group in groups %}
<h1 class="inverted-popout">{{ group.name }}</h2>
<div class="sheets">
{% for sheet in sheets %}
{% ifequal sheet.sheetGroupValue group.sheetGroupName %} <!-- This is the issue -->
<div class="sheet popout">
<h2><a href="{% url 'sheets:detail' slug='sheet.slug' slug=sheet.slug %}">
{{ sheet.name }} {{ sheet.hitPoints }} / {{ sheet.maxHitPoints }}
</a></h2>
<h3>{{ sheet.sheetGroupValue }}</h3>
<p><i>Lvl {{ sheet.level }} ({{ sheet.xp }})</i></p>
<p>{{ sheet.Class }}</p>
<p>{{ sheet.background }}</p>
<p>{{ sheet.race }}</p>
</div>
{% endifequal %}
{% endfor %}
</div>
{% endfor %}
views.py
def sheetList(request):
sheets = Sheet.objects.all().order_by('name')
groups = SheetGroup.objects.all().order_by('name')
return render(request, 'sheets/sheetList.html', { 'sheets': sheets, 'groups': groups })
models.py
class SheetGroup(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
def sheetGroupName(self):
return str(self.name)
class Sheet(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
name = models.CharField(max_length=100)
sheetGroup = models.ManyToManyField(SheetGroup)
slug = models.SlugField(default="")
# there's a bunch of fields but they do not contribute to the error
def __str__(self):
return self.name
def sheetGroupValue(self):
groups = ''
for group in self.sheetGroup.all():
groups += group.name + " "
return groups
Here is a sheet
Here is a group
And in the end Django says they are not equal (the <div class="sheet popout"> does not appear.
Any and all help would be greatly appreciated.
sheetGroupValue() is currently returning a space at the end, so the two strings aren't equal.
def sheetGroupValue(self):
groups = ''
for group in self.sheetGroup.all():
groups += group.name + " "
return groups[0:len(groups)-1]
guys.
I want to check in my django template, if request.user exists in some row of column user in my table LeagueMember. The way I found is not working.
views.py
#login_required(login_url='login/')
def search_leagues(request):
if request.method == 'POST':
return redirect('join_league')
leagues = League.objects.all()
return render(request, 'search_leagues.html', { 'allleagues': leagues })
model.py
class League(models.Model):
league_owner = models.ForeignKey('auth.User')
league_name = models.CharField(max_length=30)
creation_date = models.DateTimeField()
def is_member(self):
member = LeagueMember.objects.get(league=self)
if member:
return True
else:
return False
class LeagueMember(models.Model):
league = models.ForeignKey('League', related_name='leaguemember_league')
user = models.ForeignKey('auth.User')
search_leagues.html
{% for league in allleagues %}
<tr>
<td class="center">{{ league.league_name }}</td>
<td class="center">{{ league.leaguemember_league.count}}/{{ league.leaguesettings_league.league_number_teams }}</td>
<td class="center">{{ league.leaguesettings_league.league_eligibility }}</td>
<td class="center">{{ league.leaguesettings_league.league_lifetime }}</td>
{% if request.user in league.leaguemember_league.user %}
DO SOMETHING!!!
{% else %}
{% if league.leaguemember_league.count < league.leaguesettings_league.league_number_teams %}
{% if league.leaguesettings_league.league_eligibility == "Private" %}
<form method="post" action="{% url 'joinleague' pk=league.id %}">
<td class="center">Soliticar</td>
</form>
{% elif league.leaguesettings_league.league_eligibility == "Public" %}
<form method="post" action="{% url 'joinleague' pk=league.id %}">
<td class="center">Entrar</td>
</form>
{% endif %}
{% endif %}
{% endif %}
</tr>
{% endfor %}
This error is in this line:
{% if request.user in league.leaguemember_league.user %}
Always goes to ELSE block
Thank you all
league.leaguemember_league will not give you a LeagueMember object but a RelatedManager object (so you cannot find a user property in it, therefore your template logic will not work).
What you are trying to do is go two levels deep in your relationship (League -> LeagueMember -> User). You can't easily do this kind of logic in your template and probably need to do it in your view code instead. For example:
league_data = []
for league in League.objects.all():
league_data.append({
'league': league,
'users': User.objects.filter(leaguemember__league=league) # This gives you all the users that are related to this league
})
return render(request, 'search_leagues.html', { 'allleagues': league_data})
You then need to modify all your template logic to use this new structure:
{% for league_data in allleagues %}
# Replace league with league_data.league in all the template logic below this
In the if block you can then do:
{% if request.user in league_data.users %}
Note that this querying may not be very efficient if you have a large number of users/leagues - in which case you may need to rethink your model design.
I am trying to get a batch notification to work, but the badge throws several badges with the below code, and it does not show the number. I want the badge to display the number of content within several posts matches with an interest.
I am still a beginner at django, so please bear over with me, if this is a total bad approach.
interest.html
{% for item in interest %}
<ul class='nav nav-pills nav-stacked'>
<li><a href='/'>
<span class='badge pull-right'>
{% for word in post %}
{% if word == interest %}
{{ word.as_number }}
{% else %}
0
{% endif %}
{% endfor %}
</span>
{{ item.interest }}
</a></li>
</ul>
{% endfor %}
context_processors.py
def user_interest(request):
interest = Interests.objects.all()
interests_form = InterestsForm(request.POST or None)
post = Posts.objects.all()
if interests_form.is_valid():
new_interest = interests_form.save(commit=False)
new_interest.save()
#return HttpResponseRedirect('/')
#apparently it is not needed here
return {'interest': interest,
'interests_form': interests_form,
'post': post,
}
models.py
class Interests(models.Model):
interest = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
I'm not fully understanding, but part of your problem may be this part:
{% if word == interest %}
You're comparing a particular Post with all of your Interests (since 'interest' = Interests.objects.all()). At the very least I would change that to:
{% if word == item %}
As this iterates through your interest list (using 'item') and compares it to each 'word' in your post list.
I'm learning Python. I would like display results based on multiple selections from dropdowns.
The following code is working and returning the correct results for one dropdown. I would like to add at least one more dropdown, hopefully multiple, but I cannot fathom how to achieve passing and returning the multiple vars.
Form code
<p> <form method="get" action="">
<select name="search3">
{% for cs in course_list %}
<option value="{{ cs.pk }}">{{ cs.name }}</option>
{% endfor %}
</select>
<br/><br/>
<input type=submit value="Find staff" />
</form>
</p>
{% if employee_list %}
{{ employee_list.count }} employees matching : <strong>{{ course }}</strong><br/><br/>
{% for e in employee_list %}
{% if not e.img1 %}
<img src="/media/images/null_image.png" width="35" title="{{ e.first_name}} {{e.surname }}" />
{% else %}
<img src="{{ e.img1.url }}" width="50" title="{{ e.first_name}} {{e.surname }}"/>
{% endif %}
<a href="/employee/{{ e.slug }}" target="_blank" rel="popup" title="Details...<br />
{% for det in employee_list.employeedynamic_set.all %}
{{ det.mobile }}<br />
{{ det.depot }}<br />
{% endfor %}
"> {{ e.first_name }} {{ e.surname }}</a><br/>
{% endfor %}
{% else %}
<p>No employees matched: <strong>{{ course }}</strong></p>
{% endif %}
views.py code
# function to list training courses and participating uindividuals.
def CourseView(request):
course_list = Course.objects.all().order_by('name')
if 'search3' in request.GET:
search3 = request.GET['search3']
course = Course.objects.get(pk=search3)
else:
search3 = None
course = None
return render_to_response("course_display.html", {'course':course, 'course_list': course_list, 'search3': search3 })
Is it possible to add an another dropdown option or even multiple dropdown options and get a result. Or am I barking up the wrong tree?
UPDATE.
In order to pass one or multiple variables back to my function the code is simply the following
def CompetencyCheck(request):
course_list = Course.objects.all()
if 'search3' in request.GET:
search3 = request.GET.getlist('search3')
course = Course.objects.filter(id__in=search3).distinct().order_by()
.get() allows only the last variable passed from the web page form to be read/passed back to the function.
On the other hand, the .getlist() allows one or multiple vars to be passed back. Great, part the of problem solved.
The list of names being returned is unique in that if var1 returns 4 names and var2 returns 8 names and both vars have one common name, a list of 11 names in returned.
I want only the common names to both vars returned, i.e. 1 name to be returned.
Any ideas?
request.GET in your view is a dictionary; by doing request.GET['search3'] you're just accessing the value of its search3 key. So in your template, you should be able to just add other <select> elements with their own names and retrieve their submitted values from request.GET in the same way.
you can query using course_list only.
for example:
course_list = Course.objects.all().order_by('name')
var1 = request.POST.get('var1')
if var1:
course_list = course_list.objects.filter(some = var1)
var2 = request.POST.get('var2')
if var2:
course_list = course_list.objects.filter(some = var2)
I have 2 arrays that I would like to render in a template, one is the data to be output, the other is a formset for deleting items. since it seems django does not support boolean operators in the template tag, I have tried packaging the items, but they return the first item and the first form in 2 rows only.
How does one package such items so that they are rendered in one for loop.
my view
#login_required
def forums(request ):
post = list(forum.objects.filter(child='0')&forum.objects.filter(deleted='0'))
user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
newpostform = PostForm(request.POST)
deletepostform = PostDeleteForm(request.POST)
DelPostFormSet = modelformset_factory(forum, exclude=('child','postSubject','postBody','postPoster','postDate','childParentId'))
readform = ReadForumForm(request.POST)
if newpostform.is_valid():
topic = request.POST['postSubject']
poster = request.POST['postPoster']
newpostform.save()
newpostform = PostForm(initial = {'postPoster':user.id})
post = list(forum.objects.filter(child='0')&forum.objects.filter(deleted='0'))
else:
newpostform = PostForm(initial = {'postPoster':user.id})
if request.method == 'POST':
delpostformset = DelPostFormSet(request.POST)
if delpostformset.is_valid():
delpostformset.save()
else:
delpostformset = DelPostFormSet(queryset=forum.objects.filter(child='0', deleted='0'))
"""if readform.is_valid():
readform.save()
else:
readform = ReadForumForm()"""
return render_to_response('forum.html', {'post':( post,delpostformset.forms), 'newpostform': newpostform, })
my Template
<table class="results">
<tr class="inner_results_header"><td >Title</td><td>Date/Time</td><td>Poster</td> <td>Body</td><td><form method="post" id="form" action="" class="usertabs accfrm"><input type="submit" value="Delete" /></td></tr>
{{formset.management_form}}
{% for p, form in post %}
{% url forum_view p.postID as post_url%}
<tr class="inner_results {% if forloop.counter|divisibleby:2 %}evens{% else %}odds{% endif %}"><span onclick="document.location.href='{{post_url}}';"><td>{{ p.postSubject}}</td><td>{{p.postDate}}</td><td>{{ p.postPoster}}</td><td>{{ p.postBody|truncatewords:50}}</td></span><td>
{{ form.as_p }}
</td></tr>
{% endfor %}
<tr class="inner_results_header"><td >Title</td><td>Date/Time</td><td>Poster</td> <td>Body</td><td><input type="submit" value="Delete" /></form></td></tr>
Use zip builtin. If both post and delpostformset.forms are iterables, zip will return a list of tuples. In view:
post_and_form = zip(post, delpostformset.forms)
and in template:
{% for post, form in post_and_form %}
{% endfor %}