I'm developing a website based on Django==1.5.7
I need to paginate the ListView of a table in my application.
This is the code i'm using
On models.py:
class UsuarioFidetel(models.Model):
"""
Modelo de usuario fidetel
"""
usuario = models.CharField(max_length=30)
id_usuario = models.IntegerField()
nombre = models.CharField(max_length=255, null=True)
apellido = models.CharField(max_length=255, null=True)
tipo_cedula = models.CharField(max_length=1, null=True)
cedula = models.CharField(max_length=9, null=True)
fecha_nacimiento = models.DateField(null=True, blank=True)
sexo = models.CharField(max_length=1, null=True)
correo = models.EmailField(max_length=254, null=True)
estado_civil = models.CharField(max_length=1, null=True)
def __unicode__(self):
return self.nombre
On views.py:
class UsarioList(ListView):
model = UsuarioFidetel
template_name = 'all_list.html'
On urls.py:
url(r'^usario/$', UsarioList.as_view(model=UsuarioFidetel, paginate_by=2)),
Note the paginate_by attribute of the url, this is working just fine, but when I go to the 2nd page, or whatever page, outside the 1st one, it throws this error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:9001/usario?page=2
All is working fine, but I thought this will pass the page inside the block of my template, without major errors, can't figure out what's wrong here, maybe I need a regex on the url?
Any ideas?
Thanks in advance!
Nevermind, solved it on template, ie:
<span class="page-links">
{% if page_obj.has_previous %}
<
{% endif %}
<span class="page-current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
>
{% endif %}
</span>
Now it works the way it should
Related
I have 3 models and I need to display the area and need items only if there is at least 1 product connected. If there are no products in particular Area and Need models then it should not appear in my HTML file.
I have checked the documentation and several answers related to this topic but I cannot implement it in my script.
I also tried to create my custom filter so I can apply it directly in my template but nothing worked.
My problem is that I am getting the list of all items from Need model and I don't know how to exclude empty items from HTML page.
I will appreciate any help.
models.py
class Area(models.Model):
title = models.CharField(max_length=75, blank=False)
body = models.CharField(max_length=150, default='-', blank=False)
publish = models.DateTimeField('publish', default=timezone.now)
class Need(models.Model):
title = models.CharField(max_length=75, blank=False, null=False, help_text='max 75 characters')
body = models.CharField(max_length=150, default='-', blank=False)
publish = models.DateTimeField(default=timezone.now)
need_area = models.ForeignKey(Area, on_delete=models.CASCADE, related_name='need_area')
class ProductCategory(models.Model):
title = models.CharField(max_length=400, blank=False, null=False, help_text='max 400 characters')
body = models.TextField(default='-')
publish = models.DateTimeField('publish', default=timezone.now)
category_area = models.ForeignKey(Area, on_delete=models.CASCADE, related_name='category_area', null=True)
category_need = models.ForeignKey(Need, on_delete=models.CASCADE, related_name='category_need', null=True)
class Product(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=400, blank=False)
category = models.ForeignKey(ProductCategory, on_delete = models.CASCADE, blank=True, related_name='products')
status = models.IntegerField(choices=STATUS, default=0)
def get_absolute_url(self):
return reverse("product", kwargs={'slug': self.slug})
views.py
class Search(ListView):
template_name = 'search.html'
model = Product
queryset = Product.objects.filter(status=1)
def get_context_data(self, **kwargs):
context = super(Search, self).get_context_data(**kwargs)
filter_need = Area.objects.filter(Exists(Need.objects.filter(need_area=OuterRef('pk'))))
areas = Area.objects.prefetch_related(Prefetch('need_area', queryset=filter_need, to_attr='need_area__category_need__product')).filter(need_area__category_need__product__status=1).distinct()
context['areas'] = areas
return context
search.html
{% if areas %}
{% for area in areas %}
<div class="border mb-4 pb-4 px-2">
<h2 class="fw-bold my-2">{{area.title}}</h2>
{% for need in area.need_area.all %}
<h4 class="text-muted mt-4">{{need.title}}:</h4>
{% for product_category in need.category_need.all %}
{% for product in product_category.product.all %}
<span class="rounded-pill bg-hubble text-dark f-12 p-2">{{product.title}}</span>
{% endfor %}
{% endfor %}
{% endfor %}
</div>
{% endfor %}
{% endif %}
so I encountered a NoReverseMatch exception in my Django app. It shows me this type of exception:
Reverse for 'user-profile' with arguments '('',)' not found. 1 pattern(s) tried: ['profile/(?P[^/]+)/$']
feed_component.html code:
<div>
{% for room in rooms %}
<div>
{% if request.user == room.host %}
Edit
Delete
{% endif %}
#{{room.host.id}}
<h5>{{room.id}} --> {{room.name}}</h5>
<small>{{room.topic.name}}</small>
<hr>
</div>
{% endfor %}
So my biggest surprise is that in:
#{{room.host.id}}
#{{room.host.id}} render excatly what i want on page - id. But this part:
{% url 'user-profile' room.host.id %}"
Throws exception...
and when i change it to:
#{{room.host.id}}
There is no exceptions, it works ok but i really need that id...
urls.py
path('profile/<str:pk>/', views.userProfile, name="user-profile"),
views.py
def userProfile(request, pk):
user = User.objects.get(id=pk)
rooms = user.room_set.all()
room_messages = user.message_set.all()
topics = Topic.objects.all()
context = {'user': user, 'rooms': rooms, 'room_messages': room_messages, 'topics': topics}
return render(request, 'baseapplication/profile.html', context)
models.py
class Room(models.Model):
host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True)
name = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
participants = models.ManyToManyField(User, related_name='participants', blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
Any ideas ?
User can make hashtag. Now I want to make hashtag clickable. Bellow is my Models.py for Hashtag:
class Hashtag(models.Model):
hashtagname = models.CharField(max_length=3000, blank=True, null=True)
hashtagcount = models.IntegerField(null=True, blank=True)
post_pk = models.ManyToManyField(PostUser)
atetime = models.DateTimeField(auto_now_add=True)
date = models.DateField(auto_now_add=True)
time = models.TimeField(auto_now_add=True)
user_pk = models.IntegerField()
and in my views.py I get all the hashtags and send it by dictionary to html as bellow codes:
mosttrending = Hashtag.objects.all().order_by('-hashtagcount')[:10]
and already I have a model for all the Posts as bellow
class PostUser(models.Model):
posttype = models.CharField(max_length=3000, default='postuser')
content = models.TextField(null = True, blank= True)
media_image = models.FileField(null = True, blank= True)
media_video = models.FileField(null = True, blank= True)
per_to = models.CharField(max_length=300, null=True, blank=True, default='everyone')
status = models.CharField(max_length=3000, default='active')
date = models.DateField(auto_now_add=True)
time = models.TimeField(auto_now_add=True)
datetime = models.DateTimeField(auto_now_add=True)
like = models.IntegerField(null=True, blank=True)
comment = models.IntegerField(null=True, blank=True)
share = models.IntegerField(null=True, blank=True)
user_pk = models.IntegerField()
And in my html with a for loop I get all the PostUser:
{% for readposts in readposts %}
<p class="card-text">{{readposts.content|linebreaks}}</p>
{% endfor %}
How Can I make the link for hashtag and when a user click on the hashtag show the user the all the post?
Have you tried using a hyperlink?
{% for readposts in readposts %}
<p class="card-text"> <a href='/putyourlinkhere?hashtag=
{{readposts.content|linebreaks}}'>{{readposts.content|linebreaks}}</a></p>
{% endfor %}
In views.py:
myhashtag = request.GET.get('hashtag')
request.GET.get gets the 'hashtag' variable from the link and and saves it to myhashtag variable.
then you can perform a query to search for myhashtag and return the info.
Try to use this :-
views.py
put this in your working view :-
query = request.GET.gel('q')
object_list = PostUser.objects.filter(hashtag__hashtagname__icontains=query)
context = {'object_list ':object_list}
template
template where you've done all your view work
{% for tags in object_list %}
{{ tags }}
{{ tags.hashtagname }}
{% endfor %}
Note :- This is not clickable. I want you to try this First.
I made app_extras.py and init.py in a folder name templatetags in my django app then in the app_extras.py wrote the code bellow and worked
import re
from django import template
from django.utils.html import escape
from django.utils.safestring import mark_safe
register = template.Library()
def create_hashtag_link(tag):
url = "/tags/{}/".format(tag)
# or: url = reverse("hashtag", args=(tag,))
return '#{}'.format(url, tag)
#register.filter(name='hashchange')
def hashtag_links(value):
return mark_safe(
re.sub(r"#(\w+)", lambda m: create_hashtag_link(m.group(1)),
escape(value)))
then in HTML I have loaded the app_extras.py
{% load app_extras %}
Then in my loop html I called the function
{% for readposts in readposts %}
<p class="card-text">{{readposts.content|hashchange|linebreaks}}</p>
{% endfor %}
and also my urls.py I have added
url(r'^tags/(?P<tags>\w+)/$', views.tags, name='tags'),
then of course a view for tag which in this case my view is
def tags(request, tags):
readpostsuser = PostUser.objects.filter(content__icontains = tags).order_by('-pk')
return render(request, 'front/tags.html', {'readpostsuser':readpostsuser})
I am rendering a ManyToManyField in my template but it is shown like this :
<QuerySet [<User: Guido>]>
And I just want to print out the username without the function.
My views.py
class HotelListView(LoginRequiredMixin,ListView):
model = Hotel
def get_queryset(self):
return self.model.objects.filter(collaborateurs=self.request.user)
My template
{% for Hotel in object_list %}
{{ Hotel.collaborateurs.ALL }}
{% endfor %}
Thanks.
Edit
Models.py
class Hotel(models.Model):
collaborateurs = models.ManyToManyField(User, verbose_name="Liste des collaborateurs autorisés")
code = models.CharField(max_length=500,verbose_name="Code hôtel", null=True, blank=True)
email_manager = models.EmailField(max_length=150,verbose_name="Contact RH", null=True, blank=True)
contact_rh = models.EmailField(max_length=150,verbose_name="Contact RH", null=True, blank=True)
contact_gm = models.EmailField(max_length=150,verbose_name="Contact GM",null=True, blank=True)
payday = models.CharField(max_length=500,verbose_name="Jour de paye prévu du mois", null=True, blank=True)
hotel = models.CharField(max_length=500,verbose_name="Nom de l'hôtel")
planning = models.URLField(max_length=500, verbose_name="Planning du mois", null=True, blank=True)
def __str__(self):
return self.hotel
def get_absolute_url(self):
return reverse('hotel')
You need to iterate through the collaborators as well.
{% for Hotel in object_list %}
{% for collaborator in Hotel.collaborateurs.all %}
{{ collaborator.name }}
{% endfor %}
{% endfor %}
(Obviously replace name with the relevant field from the model.)
Hello guys I am currently working on django views and templates and met some problems.
I have a model named 'metabolites', which contains: id, name, compartment, charge and formula 5 components.
I have another model named 'Reactionsmeta', which contains: id(reactions), name, metabolie1, metabolite2, .... metabolite6. The table of this model is not filled complete, because sometimes one id corresponds to 5 metabolites, but sometimes even 20.
I write a template which can displays all the reaction, when I click on the reaction and enter the detail page, I also want to display the metabolites that involve in this reactions. My views.py and templates are written as below:
reactions_detail.html
{% extends 'Recon/Base.html' %}
{% load static %}
{% block title %}Reaction Details{% endblock %}
{% block body %}
<h1>{{ reactionsmeta.id }}</h1>
<h2>{{ reactionsmeta.name}}</h2>
<!-- Left Album Info -->
<div class="col-sm-4 col-md-3">
<div class="panel panel-default">
<div class="panel-body">
<a href="{% url 'detail_reaction' reactionsmeta.id %}">
{% if reactionsmeta.id %}
<img src="{% static "Recon/images/Logo-Technische-Universiteit-Eindhoven.jpg" %}" class="img-responsive">
{% else %}
<h3>No image to display</h3>
{% endif %}
</a>
<h1>{{ reactionsmeta.id }} <small>{{ reactionsmeta.name }}</small></h1>
</div>
</div>
</div>
views.py
from django.views import generic
from .models import Reactionsmeta,Metabolites,Reactions
from django.shortcuts import render
class IndexView(generic.ListView):
template_name = 'Recon/index.html'
context_object_name = 'Reactions_object'
def get_queryset(self):
return Reactionsmeta.objects.all()
class DetailsView(generic.DetailView):
model = Reactionsmeta
template_name = 'Recon/reactions_detail.html'
def get_context_data(self, **kwargs):
context = super(DetailsView, self).get_context_data(**kwargs)
context['metabolite'] = Metabolites.objects.all()
context['reactions'] = Reactions.objects.all()
# And so on for more models
return context
How can I write the loop in reaction_detail.html???
EDIT:
class Metabolites(models.Model):
id = models.CharField(primary_key=True, max_length=255)
name = models.CharField(max_length=255, blank=True, null=True)
compartment = models.CharField(max_length=255, blank=True, null=True)
charge = models.CharField(max_length=255, blank=True, null=True)
formula = models.CharField(max_length=255, blank=True, null=True)
notes = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'Metabolites'
class Reactionsmeta(models.Model):
id = models.CharField(primary_key=True, max_length=255)
name = models.CharField(max_length=255, blank=True, null=True)
metabolite1 = models.ForeignKey('Metabolites', db_column='metabolite1',
blank=True, null=True, on_delete=models.CASCADE)
stoichiometry1 = models.IntegerField(blank=True, null=True)
metabolite2 = models.CharField(max_length=255, blank=True, null=True)
stoichiometry2 = models.IntegerField(blank=True, null=True)
metabolite3 = models.CharField(max_length=255, blank=True, null=True)
stoichiometry3 = models.CharField(max_length=255, blank=True, null=True)
......
stoichiometry55 = models.CharField(max_length=255, blank=True, null=True)
metabolite56 = models.CharField(max_length=255, blank=True, null=True)
stoichiometry56 = models.CharField(max_length=255, blank=True, null=True)
metabolite57 = models.CharField(max_length=255, blank=True, null=True)
stoichiometry57 = models.CharField(max_length=255, blank=True, null=True)
metabolite58 = models.CharField(max_length=255, blank=True, null=True)
stoichiometry58 = models.CharField(max_length=255, blank=True, null=True)
metabolite59 = models.CharField(max_length=255, blank=True, null=True)
stoichiometry59 = models.CharField(max_length=255, blank=True, null=True)
metabolite60 = models.CharField(max_length=255, blank=True, null=True)
stoichiometry60 = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'ReactionsMeta'
I don't see a great way to do this since each metabolite has its own field and isn't necessarily a foreign key. It'd be easier if the metabolite were in a ManyToMany field with through defining the stoichiometry.
Django's ManyToMany Relationship with Additional Fields
https://docs.djangoproject.com/en/2.0/topics/db/examples/many_to_many/
That said, in the template you can display a Reactionsmeta metabolite1 and stoichiometry one by :
{% if reactionsmeta.metabolite1 %}
Metabolite: {% reactionsmeta.metabolite1 %}
Stoichiometry: {% reactionsmeta.stoichiometry1 %}
{% endif %}
{% if reactionsmeta.metabolite2 %}
Metabolite: {% reactionsmeta.metabolite2 %}
Stoichiometry: {% reactionsmeta.stoichiometry2 %}
{% endif %}
...
{% if reactionsmeta.metabolite60 %}
Metabolite: {% reactionsmeta.metabolite60 %}
Stoichiometry: {% reactionsmeta.stoichiometry60 %}
{% endif %}
Problems with the above:
It's terrably repetative
If the fields are in fact Foreign Keys their raw values wont't mean anything to the user.
EDIT: Response to comment that CharFields are in fact FKs.
So I think you need to query db for the information about the metabolites in the view and return that to the template. I think, by design, templates are not supposed to be able to access the db.
EDIT: I'm afraid you're going to have to learn how to write custom views. It's really not bad but it's hard to do some of the things you're attempting just using the generics.
https://docs.djangoproject.com/en/2.0/topics/http/views/