How can I paginate using multiple filters in Django CBV? I have some filters in my view and form and I don't know how to paginate it. Everything that I've tried has failed.
Here my code.
models.py
class Lei(models.Model):
CHOICE_TIPO_LEI = (
('complementar', 'Lei complementar'),
('ordinaria', 'Lei ordinária'),
('decreto', 'Decreto'),
('portaria', 'Portaria'),
('convenio', 'Convênios Municipais'),
)
numero = models.CharField(max_length=6)
tipo_lei = models.CharField(u'Tipo do documento', max_length=15, choices=CHOICE_TIPO_LEI)
ano = models.CharField(max_length=4)
titulo = models.TextField()
arquivo = FileBrowseField("Arquivo PDF", max_length=200, extensions=[".pdf",".doc", ".xls", ".docx", ".xlsx"], directory="leis/", blank=True, null=True)
publicacao = models.DateTimeField(u'publicação', auto_now=True, blank=True)
class Meta:
db_table = "tb_lei"
verbose_name = "Lei"
verbose_name_plural = "Leis"
def __str__(self):
return self.titulo
views.py
class LeisListView(ComunsNoticiasMixin, ListView):
model = Lei
template_name = 'leis/leis.html'
context_object_name = 'leis'
def get_context_data(self, **kwargs):
context = super(LeisListView, self).get_context_data(**kwargs)
context["an"] = Lei.objects.values('ano').distinct().order_by('-ano')
context["tl"] = Lei.objects.values('tipo_lei').distinct().order_by('tipo_lei')
return context
class BuscaLeiListView(ComunsNoticiasMixin, ListView):
model = Lei
template_name = 'leis/busca-leis.html'
context_object_name = 'busca_leis'
paginate_by = 1
def get_queryset(self, **kwargs):
numero = self.request.GET.get('n')
ano = self.request.GET.get('a')
tipo_lei = self.request.GET.get('t')
palavra = self.request.GET.get('p')
leis = Lei.objects.all().order_by('-ano', '-numero')
if numero:
leis = leis.filter(numero=numero)
if ano:
leis = leis.filter(ano=ano)
if tipo_lei:
leis = leis.filter(tipo_lei=tipo_lei)
if palavra:
leis = leis.filter(titulo__icontains=palavra)
return leis
form.html
<form method="get" action="{% url 'leis:busca_lei_view' %}">
<div class="form-group">
<select name="t" class="form-control">
<option value="">Tipo do documento</option>
{% for l in tl %}
<option value="{{ l.tipo_lei }}">
{% if l.tipo_lei == "complementar" %} Leis complementares
{% elif l.tipo_lei == "ordinaria" %} Leis ordinárias
{% elif l.tipo_lei == "decreto" %} Decretos
{% elif l.tipo_lei == "convenio" %} Convênios municipais
{% elif l.tipo_lei == "portaria" %} Portarias
{% endif %}
</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<input name="n" type="text" class="form-control" placeholder="numero da lei, portaria ou decreto" size="10" maxlength="30">
</div>
<div class="form-group">
<select name="a" class="form-control">
<option value="">ano</option>
{% for l2 in an %}
<option value="{{ l2.ano }}">{{ l2.ano }}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<button value="{{ search_term }}" class="btn btn-info">pesquisar</button>
</div>
<hr />
<div class="form-group">
<label for="t"><strong>Ou digite um termo a ser pesquisado</strong></label>
<input name="p" class="form-control" type="text" placeholder="digite um termo a ser pesquisado" size="20" maxlength="30">
</div>
<button value="{{ search_term }}" class="btn btn-info">Pesquisar</button>
result.html
<div class="row">
<div class="col-xs-12">
{% if busca_leis %}
{% for lb in busca_leis %}
<h4 ><a href="{{ lb.arquivo.url }}" class="text-primary">
{% if lb.tipo_lei == "complementar" %}Lei complementar n° {% elif lb.tipo_lei == "ordinaria" %} Lei ordinária nº {% elif lb.tipo_lei == "decreto" %} Decreto nº {% elif lb.tipo_lei == "convenio" %} Convênio municipal {% else %} Portaria nº{% endif %} {{ lb.numero }} de {{ lb.ano }}</a>
</h4>
<p class="post-content">{{ lb.titulo|safe }}</p>
<br />
{% endfor %}
<br />
{% else %}
<br /><br />
<div class="alert alert-warning" role="alert">
<h5>
O termo pesquisado não foi encontrado. Utilize os filtros para realizar a pesquisar novamente.
</h5>
voltar
</div>
{% endif %}
</div>
{% if is_paginated %}
<ul class="pagination">
{% if page_obj.has_previous %}
<li>«</li>
{% else %}
<li class="disabled"><span>«</span></li>
{% endif %}
{% for i in paginator.page_range %}
{% if page_obj.number == i %}
<li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
{% else %}
<li>{{ i }}</li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li>»</li>
{% else %}
<li class="disabled"><span>»</span></li>
{% endif %}
</ul>
{% endif %}
The existing querystring is being dropped when you click on the pagination, so you need to have a way to carry that information through.
The best option would be to bring that information through.
Start by adding the "django.core.context_processors.request" to settings.py
## settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
)
Now, you have access to https://docs.djangoproject.com/en/1.8/ref/request-response/#querydict-objects.
In the template change the line:
<a href="?page={{ page_obj.next_page_number }}">
to
<a href="?page={{ page_obj.next_page_number }}{% for key, value in request.GET.items %}{% if key != page %}&{{key}}={{value}}{% endif %}{% endfor %}"
This will loop through the keys in the querystring and ignore the pa
Related
I am having a problem in categorize Posts. I have categories in Post Model, Please help me solve this issue!
MODELS.PY
html= "html"
css= "css"
python= "python"
javascript = "javascript"
Lang=(
(html,"HTML"),
(css,"CSS"),
(python,"PYTHON"),
(javascript,"JAVASCRIPT")
)
Broilerplate = "Broilerplate"
Simple_Tags = "Simple Tags"
Elements = "Elements"
Webpages = "Webpages"
Category = (
(Broilerplate,"BROILERPLATE"),
(Simple_Tags,"Simple tags"),
(Elements,"Elements"),
(Webpages,"Webpages")
)
class Post(models.Model):
title = models.CharField(max_length=75)
subtitle = models.CharField(max_length=150)
language_1 = models.CharField(max_length=100, choices=Lang, default=html)
content_1= models.TextField(blank=True)
language_2 = models.CharField(max_length=100, choices=Lang,blank=True)
content_2= models.TextField(blank=True)
language_3 = models.CharField(max_length=100, choices=Lang,blank=True)
content_3= models.TextField(blank=True)
language_4 = models.CharField(max_length=100, choices=Lang,blank=True)
content_4= models.TextField(blank=True)
language_5 = models.CharField(max_length=100, choices=Lang,blank=True)
content_5= models.TextField(blank=True)
category= models.CharField(max_length=100, choices=Category, default=Broilerplate)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.title
# def update(self):
# updated_at = timezone.now()
# self.save(updated_at)
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk':self.pk})
VIEWS.PY
def search_by_category(request, category):
if request.post.objects.filter(pk=request.post.id).first().category == 'Broilerplate':
nor = request.post.objects.filter(pk=request.post.id).first().category
print(nor)
posts = Post.objects.filter(category='Broilerplate')
category = posts.first().category
print(category)
context = {'posts': posts, 'title': category , 'category': category}
return render(request, 'category.html', context)
else:
context = {'title': category , 'category': category}
return render(request, 'category.html', context)
URLS.PY
urlpatterns = [
path('html/',PostListView.as_view(), name='CodeWriter_Homepage'),
path('python/',views.CodeWriter_homepage_python, name='CodeWriter_Homepage_python'),
path('search/', views.search, name='search'),
path('categroize-by/<str:category>/', views.search_by_category, name='search_by_category'),
path('post-details/<int:pk>/',PostDetailView.as_view(), name='Post_details_page'),
path('post-update/<int:pk>/',PostUpdateView.as_view(), name='Post_update_page'),
path('post-delete/<int:pk>/',PostDeleteView.as_view(), name='Post_delete_page'),
path('user/<str:username>/', UserPostListView.as_view(), name='user-post'),
path('new-post/',PostCreateView.as_view(), name='New-post_page')
]
CATEGORY.html
How can I get the data of the post category in views.py?That will help me very much!
{% block main_post_body %}
<main class="post-body normal" >
<p class="post-heading"> Post for <b>{{ category }}</b> :</p>
{% comment %} <h1 class="mb-3">Search results for <b>{{category}}</b>: </h1> {% endcomment %}
{% comment %} {% if posts|length < 1 %}
<h3>No search results found</h3>
<p>Your search results for <b>{{ query }}</b> is not found.</p>
{% endif %} {% endcomment %}
{% for post in posts %}
<div class="row">
<div class="col span-8-of-12 card">
<div class="row">
<!-- <div class="triangle"></div>
<div class="person-info-card">
<div class="row">
<div class="col"><img src="{% static 'resoures/css/img/Me.jpg' %}" alt=""></div>
<div class="col">
<p>Ketan Vishwakarma</p>
<p class="post-no">126 Posts | 1k Followers</p>
</div>
</div>
</div> -->
<div class="col span-1-of-12">
<div class="person-img" id="person-info-card-toggle">
<img src="{{ post.author.profile.image.url }}" alt="" />
</div>
</div>
<div class="col span-7-of-12">
<h3>{{ post.title }} </h3>
<h4>{{ post.subtitle }}</h4>
</div>
<div class="col span-1-of-12">
<span class="ion-md-heart-empty"></span>
</div>
<div class="col span-1-of-12">
<span class="ion-md-add-circle-outline"></span>
</div>
<div class="col span-1-of-12 share">
<span class="ion-md-share"></span>
<ul class="dropdown-list-share">
<li><span class="ion-md-copy"> Copy</span></li>
<li><span class="ion-logo-whatsapp"> Share on Whatsapp</span></li>
<li><span class="ion-logo-facebook"> Share on facebook</span></li>
<li><span class="ion-md-more"> More</span></li>
</ul>
</div>
<div class="col span-1-of-12">
<span class="ion-md-menu"></span>
<ul class="dropdown-list">
<li>Doesn't work</li>
<li>Report</li>
<li>Report</li>
</ul>
</div>
</div>
<div class="tabs">
<ul class="tabs-list">
<li class="active">{{ post.language_1 }}</li>
{% if post.content_2 == "" %}
{% else %}
<li class="not-clickable hint--info" aria-label="To view this click Read more">{{ post.language_2 }}</li>
{% endif %}
{% if post.content_3 == "" %}
{% else %}
<li class="not-clickable hint--info" aria-label="To view this click Read more">{{ post.language_3 }}</li>
{% endif %}
{% if post.content_4 == "" %}
{% else %}
<li class="not-clickable hint--info" aria-label="To view this click Read more">{{ post.language_4 }}</li>
{% endif %}
{% if post.content_5 == "" %}
{% else %}
<li class="not-clickable hint--info" aria-label="To view this click Read more">{{ post.language_5 }}</li>
{% endif %}
<ul class="categories">
<abbr title="Categiores">
<a href="">
<span class="ion-md-code-working"></span>
{{ post.category }}
</a>
</abbr>
<!-- <li>Broilerplate</li> -->
</ul>
</ul>
<div id="tab1" class="tab active">
<p>
<pre><code class="language-{{ post.language_1 }}">
{{ post.content_1 }}
</code></pre>
</p>
</div>
<div id="tab2" class="tab">
<p>
<pre><code class="language-{{ post.language_2 }}">
{{ post.content_2 }}
</code></pre>
</p>
</div>
<div id="tab3" class="tab">
<p>
<pre><code class="language-{{ post.language_3 }}">
{{ post.content_3 }}
</code></pre>
</p>
</div>
<div id="tab4" class="tab">
<p>
<pre><code class="language-{{ post.language_4 }}">
{{ post.content_4 }}
</code></pre>
</p>
</div>
<div id="tab5" class="tab">
<p>
<pre><code class="language-{{ post.language_5 }}">
{{ post.content_5 }}
</code></pre>
</p>
</div>
</div>
<span class="ion-md-arrow-round-down"> Read More</span>
<h6>{{ post.date_posted|date:"F d, Y" }}</h6>
</div>
<div class="col span-4-of-12 main-card ">
<div class="card-small">
<h1>Result: </h1>
<div class="result-box">
<iframe src="" frameborder="0">just for fun</iframe>
</div>
<h6>{{ post.date_posted|date:"F d, Y" }}</</h6>
</div>
</div>
</div>
{% endfor %}
</main>
{% if is_paginated %}
{% if page_obj.has_previous %}
<a class="btn btn-outline-info mb-4" href="?page=1">First</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a>
{% endif %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
<a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a>
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
<a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a>
{% endif %}
{% endif %}
{% endblock main_post_body %}
NoteI have registered the Post model in admin.py
Tell me the solution to this problem I cannot get the solution I have been trying it for so long and am stuck on this.
So I'm trying to use pagination, When I visit the page I get MultiValueDictKeyError at /products/
'page', and when I go to localhost:8000/thatpage/?page=1 then I get TypeError at /products/
'Paginator' object is not callable.
This error occurs when i visit the page and i don't know what i'm doing wrong, Any help would be great.
views.py
def showproducts(request):
oof = CartItem.objects.filter(user=request.user).values_list('book', flat=True)
lmao = OrderItem.objects.filter(user=request.user).values_list('book', flat=True)
hehe = CartItem.objects.filter(user=request.user)
category = Category.objects.all()
haha = Paginator(Book, 2)
page = request.GET['page']
fianlprice = 0
for item in hehe:
fianlprice += item.book.price
# books = Book.objects.all()
books = haha(page)
return render(request, 'main/products.html', {'books':books, 'price':fianlprice, 'cart':oof, 'order':lmao, 'category':category})
products.html
<h1>Products</h1>
<h1>{{ error }}</h1>
{% if user.is_authenticated %}
<h1>Your cart currently costs ${{ price }}</h1>
{% else %}
<h1>Please login to view your cart</h1>
{% endif %}
<form method="GET" action="/search/">
<label>Choose a category</label>
<select name="category" id="category">
<option value="All" selected>All</option>
{% for name in category %}
<option value="{{ name.name }}">{{ name.name }}</option>
{% endfor %}
</select>
<input type="text" placeholder="Search here" name="search" id="search">
<button type="submit">Search</button>
</form>
{% for book in books %}
<h3>{{ book.name }}</h3>
<img src= "/media/{{ book.image }}" alt="">
<p>{{ book.description }}</p>
{% if not user.is_authenticated %}
<p>Please login</p>
{% else %}
{% if book.id in cart %}
<form method="POST" action="/removefromcartforhome/">
{% csrf_token %}
<button type="submit" name="removeid" value="{{ book.id }}">remove item from cart</button>
</form>
{% elif book.id in order %}
<h3>You already own this</h3>
{% else %}
<form method="POST" action="/addtocartforhome/">
{% csrf_token %}
<button type="submit" name="bookid" value="{{ book.id }}">Add to cart</button>
</form>
{% endif %}
{% endif %}
{% endfor %}
{% if books.has_other_pages %}
{% if listing.has_previous %}
<li class="page-item">
«
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link">«</a>
</li>
{% endif %}
{% for i in books.paginator.page_range %}
{% if books.number == i %}
<li class="page-item active">
<a class="page-link">{{i}}</a>
</li>
{% else %}
<li class="page-item">
{{i}}
</li>
{% endif %}
{% endfor %}
{% if books.has_next %}
<li class="page-item">
»
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link">»</a>
</li>
{% endif %}
{% else %}
{% endif %}
The request.GET['page'] will raise an error if the ?page=… querystring is missing. You can work with request.GET.get('page') to return None in case the it is missing.
Furthermore you can not call haha(page), you call the .page(…) method [Django-doc] or the .get_page(…) method [Django-doc], so:
from django.http import Http404
def showproducts(request):
oof = CartItem.objects.filter(user=request.user).values_list('book', flat=True)
lmao = OrderItem.objects.filter(user=request.user).values_list('book', flat=True)
hehe = CartItem.objects.filter(user=request.user)
category = Category.objects.all()
haha = Paginator(Book, 2)
page = request.GET.get('page') or 1 # ← 1 in case ?page=… does not exists
try:
page = int(page)
except ValueError:
raise Http404
fianlprice = 0
for item in hehe:
fianlprice += item.book.price
# books = Book.objects.all()
books = haha.page(page) # ← use the .page(…) method
return render(request, 'main/products.html', {'books':books, 'price':fianlprice, 'cart':oof, 'order':lmao, 'category':category})
So I'm trying to use pagination in django, When I click on previous it takes me to localhost:8000/thatpage/?page= when it is supposed to take me to the previous page, It also gives me error on that page. I have tried handling it in my views.py but it doesn't work.
I have also tried using books_obj.previous_page_number but that doesn't work too.
I'm using Django 3.1
views.py
def showproducts(request):
oof = CartItem.objects.filter(user=request.user).values_list('book', flat=True)
lmao = OrderItem.objects.filter(user=request.user).values_list('book', flat=True)
hehe = CartItem.objects.filter(user=request.user)
category = Category.objects.all()
haha = Paginator(Book.objects.all(), 2)
page = request.GET.get('page')
if page is None or "":
page = 1
fianlprice = 0
for item in hehe:
fianlprice += item.book.price
# books = Book.objects.all()
books = haha.page(page)
return render(request, 'main/products.html', {'books':books, 'price':fianlprice, 'cart':oof, 'order':lmao, 'category':category})
products.html
<h1>Products</h1>
<h1>{{ error }}</h1>
{% if user.is_authenticated %}
<h1>Your cart currently costs ${{ price }}</h1>
{% else %}
<h1>Please login to view your cart</h1>
{% endif %}
<form method="GET" action="/search/">
<label>Choose a category</label>
<select name="category" id="category">
<option value="All" selected>All</option>
{% for name in category %}
<option value="{{ name.name }}">{{ name.name }}</option>
{% endfor %}
</select>
<input type="text" placeholder="Search here" name="search" id="search">
<button type="submit">Search</button>
</form>
{% for book in books %}
<h3>{{ book.name }}</h3>
<img src= "/media/{{ book.image }}" alt="">
<p>{{ book.description }}</p>
{% if not user.is_authenticated %}
<p>Please login</p>
{% else %}
{% if book.id in cart %}
<form method="POST" action="/removefromcartforhome/">
{% csrf_token %}
<button type="submit" name="removeid" value="{{ book.id }}">remove item from cart</button>
</form>
{% elif book.id in order %}
<h3>You already own this</h3>
{% else %}
<form method="POST" action="/addtocartforhome/">
{% csrf_token %}
<button type="submit" name="bookid" value="{{ book.id }}">Add to cart</button>
</form>
{% endif %}
{% endif %}
{% endfor %}
{% if books.has_other_pages %}
{% if books.has_previous %}
<li class="page-item">
«
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link">«</a>
</li>
{% endif %}
{% for i in books.paginator.page_range %}
{% if books.number == i %}
<li class="page-item active">
<a class="page-link">{{i}}</a>
</li>
{% else %}
<li class="page-item">
{{i}}
</li>
{% endif %}
{% endfor %}
{% if books.has_next %}
<li class="page-item">
»
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link">»</a>
</li>
{% endif %}
{% else %}
<p>no pages</p>
{% endif %}
Change this code from:
if page is None or "":
page = 1
to
page = request.GET.get('page', None)
if page == None or page == "":
page = 1
# or
if not page:
page = 1
Update
You can use http referee to redirect to previous page:
if not page:
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
I want to display 1 button in the for-loop, but i get as many buttons as many i have created groups. So.. when i created 3 groups where i'm one of the members, i got 3 buttons under every group i have. The problem is with this first loop in my code, but i don't know how to solve this.
Problem is in loop:
{% for z in mem %}
When i create any memberships it's like:
m = Membership.objects.create(person="damian", group="name_group", leader=True) / or False
Thanks for any help!
groups.html:
{% for g in gr %}
<div class="jumbotron">
<div class="jumbo2">
<form method="POST" class="post-form"> {% csrf_token %}
<p id="name"><b>Group's name:</b> {{g.name}}</p><br>
{% for member in g.members.all %}
<p><b>Member:</b> {{member.name}} </p>
{% endfor %}
<br>
<span class="desc2">Group's description:</span>
<p id="desc">{{g.description}}</p><br>
{% for z in mem %}
{% if z.leader == False %}
<button style="float: right" type="submit" name = "leave" value = "{{g.name}}" class="save btn btn-default">Leave</button>
{% elif z.leader == True %}
<button style="float: right" type="submit" name = "delete" value = "{{g.name}}" class="save btn btn-default">Delete</button>
{% endif %}
{% endfor %}
</form>
<br><br>
<p>
{% if messages %}
{% for message in messages %}
<p>{{ message }}</p>
{% endfor %}
{% endif %}
</p>
</div>
</div>
{% endfor %}
views.py:
cvs = Cv.objects.all()
cv = Cv.objects.filter(author = request.user)
per = Person.objects.all()
gr = Group.objects.filter(members__name=request.user)
perr = Person.objects.filter(name=request.user)
mem = Membership.objects.filter(group = gr, person = perr)
form = GroupForm()
context = {
'gr': gr,
'per':per,
'mem':mem,
'form': form,
'cvs':cvs,
'cv':cv,
}
return render(request, 'groups.html', context)
models.py:
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self): # __unicode__ on Python 2
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
description = models.TextField(max_length=350)
def __str__(self): # __unicode__ on Python 2
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person)
leader = models.BooleanField(default=False)
group = models.ForeignKey(Group)
Ok, i replace my groups and used only membership objects. Here's my working code:
{% for z in mem %}
<div class="jumbotron">
<div class="jumbo2">
<form method="POST" class="post-form"> {% csrf_token %}
<p id="name"><b>Group's name:</b> {{z.group}}</p><br>
{% for member in z.group.members.all %}
<p><b>Member:</b> {{member.name}} </p>
{% endfor %}
<br>
<span class="desc2">Group's description:</span>
<p id="desc">{{z.group.description}}</p><br>
{% if z.leader == False %}
<button style="float: right" type="submit" name = "leave" value = "{{z.group}}" class="save btn btn-default">Leave</button>
{% elif z.leader == True %}
<button style="float: right" type="submit" name = "delete" value = "{{z.group}}" class="save btn btn-default">Delete</button>
{% endif %}
</form>
<br><br>
<p>
</p>
</div>
</div>
{% endfor %}
I'm writing a basic messaging function inside my app and it does what it's suppose to do. It sends, receives and sort messages in inbox and outbox, and I wanted it to show the nicknames of those who send (TO: 'nickname') and those who receive the message (FROM: 'nickname')
SOLVED
class Message(db.Model):
id = db.Column(db.Integer, primary_key = True)
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime)
for_id = db.Column(db.Integer)
**for_nickname = db.Column(db.String(140))**
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
def __repr__(self): # pragma: no cover
return '<Message %r>' % (self.body)
I just added one more field in my table for the nickname, so I can access it from the posted data. I felt that writing 2 more queries and comparing them to get this same result is too much for something like this.
Edited:
the view:
#app.route('/poraki', methods = ['GET', 'POST'])
#login_required
def poraki(page=1):
form = PostMessage()
nick = form.nickname.data
nickname = User.query.filter_by(nickname = nick).first()
if form.validate_on_submit():
m = Message(body = form.post.data,
timestamp = datetime.utcnow(),
author = g.user,
for_id = nickname.id)
db.session.add(m)
db.session.commit()
flash(gettext(u'Вашата порака е пратена!'))
return redirect(url_for('poraki'))
#inbox
sent = User.query.filter_by(nickname = g.user.nickname).first()
all_inbox = Message.query.filter_by(for_id = sent.id).order_by(Message.timestamp.desc()).paginate(page, POSTS_PER_PAGE, False)
#sent
all_sent = Message.query.filter_by(user_id = sent.id).order_by(Message.timestamp.desc()).paginate(page, POSTS_PER_PAGE, False)
return render_template('messages.html', form = form, posts1 = all_sent, posts2 = all_inbox, title = u'Пораки')
PostMessage():
class PostMessage(Form):
nickname = TextField('nickname', validators = [Required()])
post = TextField('post', validators = [Required()])
message.html template:
<td width="70px"><img src="{{post.author.avatar(70)}}" /></td>
<td>
{% autoescape false %}
{% if prateni == 1 %}
<p>{{ _('До: %(nickname)s ', nickname = '%s' % (url_for('user', nickname = post.for_id), post.for_id)) }}</p>
{% else %}
<p>{{ _('Од: %(nickname)s ', nickname = '%s' % (url_for('user', nickname = post.author.nickname), post.author.nickname)) }}</p>
{% endif %}
{% endautoescape %}
<p><strong><span id="post{{post.id}}">{{post.body}}</span></strong></p>
{% autoescape false %}
<p>{{ _('%(when)s', when = momentjs(post.timestamp).fromNow() ) }} </p>
{% endautoescape %}
<!-- {% if post.author.id == g.user.id %}
<div>{{ _('Избриши') }}</div>
{% endif %} -->
</td>
messages.html template:
<div class="well">
<form class="form-horizontal" action="" method="post" name="post">
{{form.hidden_tag()}}
<div class="control-group{% if form.errors.post %} error{% endif %}">
<label class="control-label" for="nickname">{{ _('До:') }}</label>
<div class="controls">
{{ form.nickname(size = 30, maxlength = 140) }}
{% for error in form.errors.nickname %}
<span class="help-inline">[{{error}}]</span><br>
{% endfor %}
</div>
</div>
<div class="control-group{% if form.errors.post %} error{% endif %}">
<label class="control-label" for="post">{{ _('Порака:') }}</label>
<div class="controls">
{{ form.post(cols = 64, rows = 4, class = "span4") }}
{% for error in form.errors.post %}
<span class="help-inline">[{{error}}]</span><br>
{% endfor %}
</div>
</div>
<div class="control-group">
<div class="controls">
<input class="btn btn-primary" type="submit" value="{{ _('Прати!') }}">
</div>
</div>
</form>
</div>
<table class="table">
<tr>
<td width=50%> Пратени пораки {{ proba }}
{% set prateni = 1 %}
{% for post in posts1.items %}
{% include 'message.html' %}
{% endfor %}
</td width=50%>
<td> Примени пораки
{% set prateni = 0 %}
{% for post in posts2.items %}
{% include 'message.html' %}
{% endfor %}
</td>
</tr>
</table>