How to add pagination in search.html - django - django

how to create pagination in search.html ?
i want show 4 posts per page
what must I do now ?
any help please and thanks
this is my views.py :
class SearchView(ListView):
template_name = 'website_primary_html_pages/search.html'
paginate_by = 20
count = 0
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['count'] = self.count or 0
context['query'] = self.request.GET.get('q')
return context
def get_queryset(self):
request = self.request
query = request.GET.get('q', None)
if query is not None:
android_results = Android.objects.search(query)
linux_results = Linux.objects.search(query)
tech_results = Tech.objects.search(query)
mobile_results = Mobile.objects.search(query)
windows_results = Windows.objects.search(query)
# combine querysets
queryset_chain = chain(
android_results,
linux_results,
tech_results,
mobile_results,
windows_results
)
qs = sorted(queryset_chain,
key=lambda instance: instance.pk,
reverse=True)
self.count = len(qs) # since qs is actually a list
return qs
return Android.objects.none() # just an empty queryset as default
and here is my search.html :
{% for object in object_list %}
{% with object|class_name as klass %}
{% if klass == 'Mobile' %}
<div class="card-deck">
<div class="card mb-3" style="max-width: 800px;">
<div class="row no-gutters">
<div class="col-md-4">
</div>
<div class="col-md-8">
<div class="card-body">
<b>{{ object.name }}</b></h5>
<p class="card-text" id="font_control_for_all_pages">{{ object.app_contect|truncatechars_html:153|safe}}</p>
</div>
<div class="card-footer">
<small class="text-muted" id="date_post_control">{{ object.post_date}}</small>
<small class="firstsmall"><a class="bg-orange" href="{% url 'mobile' %}" id="tag_name_control">هواتف</a></small>
</div>
</div>
</div>
</div>
</div>
<hr>
{% elif klass == 'Linux' %}
<div class="card-deck">
<div class="card mb-3" style="max-width: 800px;">
<div class="row no-gutters">
<div class="col-md-4">
</div>
<div class="col-md-8">
<div class="card-body">
<b>{{ object.name }}</b></h5>
<p class="card-text" id="font_control_for_all_pages">{{ object.app_contect|truncatechars_html:153|safe}}</p>
</div>
<div class="card-footer">
<small class="text-muted" id="date_post_control">{{ object.post_date}}</small>
<small class="firstsmall"><a class="bg-orange" href="{% url 'linux' %}" id="tag_name_control">لينكس</a></small>
</div>
</div>
</div>
</div>
</div>
<hr>
{% else %}
{% endif %}
{% endwith %}
{% empty %}
<div class='row'>
<div class='col-12 col-md-6 mx-auto my-5 py-5'>
<form method='GET' class='' action="{% url 'search' %}">
<div class="input-group form-group-no-border mx-auto" style="margin-bottom: 0px; font-size: 32px;">
<span class="input-group-addon cfe-nav" style='color:#000'>
<i class="fa fa-search" aria-hidden="true"></i>
</span>
<input type="text" name="q" data-toggle="popover" data-placement="bottom" data-content="Press enter to search" class="form-control cfe-nav mt-0 py-3" placeholder="Search..." value="" style="" data-original-title="" title="" autofocus="autofocus">
</div>
</form>
</div>
</div>
{% endfor %}
what i must add in html page and views.py ?
i want This display for example , like this example :
Page 2 of 3. next back
how to do this and thanks :)

Change object_list in your template to page_obj:
{% for object in page_obj %}
Correct field paginate_by in your SearchView:
class SearchView(ListView):
template_name = 'website_primary_html_pages/search.html'
paginate_by = 4
Add paginator at the bottom of your template, all the pages of such "search paginator" should have all the queries that you search had, for example:
{% 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 }}{% for k,v in request.GET.items %}{% if k != 'page' %}&{{ k }}={{ v }}{% endif %}{%endfor%}">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 }}{% for k,v in request.GET.items %}{% if k != 'page' %}&{{ k }}={{ v }}{% endif %}{%endfor%}">{{ 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 }}{% for k,v in request.GET.items %}{% if k != 'page' %}&{{ k }}={{ v }}{% endif %}{%endfor%}">{{ num }}</a>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}{% for k,v in request.GET.items %}{% if k != 'page' %}&{{ k }}={{ v }}{% endif %}{%endfor%}">Next</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}{% for k,v in request.GET.items %}{% if k != 'page' %}&{{ k }}={{ v }}{% endif %}{%endfor%}">Last</a>
{% endif %}
{% endif %}

Related

Adding a tag to a pagination element django

When creating a pagination, everything works as it should. Added (?page= page number selection) pagination.
How can I add the pagination page number to its object?
When selecting an object and reloading the page, I need it to be spelled out in the URL (/?page=pagination number).
And the pagination remained on the selected page.
class MovieShow(DetailView):
model = Movie
template_name = 'movies/movie_play.html'
context_object_name = 'movie'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['object_list'] = Movie.objects.filter(course__slug=self.kwargs['course_slug'])
context['title'] = context['movie']
paginator = Paginator(context['object_list'], 1)
page = self.request.GET.get('page')
try:
context['object_list'] = paginator.page(page)
except PageNotAnInteger:
context['object_list'] = paginator.page(1)
except EmptyPage:
context['object_list'] = paginator.page(paginator.num_pages)
return context
This is how I present pagination in the template
<div class="pagination" id="pagination">
<span class="step-links" >
{% if object_list.has_previous %}
<a class="page-link" href="?page=1"> << </a>
<a class="page-link" href="?page={{ object_list.previous_page_number }}"> < </a>
{% endif %}
<span class="current">
{{ object_list.number }} из {{ object_list.paginator.num_pages }}
</span>
{% if object_list.has_next %}
<a class="page-link" href="?page={{ object_list.next_page_number }}"> > </a>
<a class="page-link" href="?page={{ object_list.paginator.num_pages }}"> >> </a>
{% endif %}
</span>
And so I have a search of the elements inside the pagination, on which I want to hang the pagination page number.
I really hope I asked the question correctly.
I will be glad of any help!
<div class="video_courses" id="block-posts">
{% for c in object_list %}
<a class="a_hover" href="{{ c.get_absolute_url }}">
<div class="video_courses_block">
<div class="video_courses_block_img"><img src="{{ c.poster.url }}" alt=""></div>
<div class="video_courses_block_text">
<div class="video_courses_block_text_title"><h2>[ {{ c.author }} ] {{ c.title }}</h2></div>
<div class="video_courses_block_text_navigation">
<div class="video_courses_block_text_left">{{ c.category }}</div>
<div class="video_courses_block_text_rig">{{ course.movie_set.count }}</div>
</div>
</div>
</div>
</a>
{% endfor %}
{% include 'pagination.html' %}
You just need to add if to the link and specify the page number
{% for c in object_list %}
{% if object_list.number %}
<a class="a_hover" href="{{ c.get_absolute_url }}?page={{ object_list.number }}">
{% endif %}
<div class="video_courses_block">
<div class="video_courses_block_img"><img src="{{ c.poster.url }}" alt=""></div>
<div class="video_courses_block_text">
<div class="video_courses_block_text_title">
<h2>[ {{ c.author }} ] {{ c.title }}</h2>
</div>
<div class="video_courses_block_text_navigation">
<div class="video_courses_block_text_left">{{ c.category }}</div>
<div class="video_courses_block_text_rig">{{ course.movie_set.count }}</div>
</div>
</div>
</div>
</a>
{% endfor %}
</div>
{% include 'pagination.html' %}

How to add paginator and filter in your website?

I'm doing a project in which I need to display cars and the user is allowed to filter their queries based on price, make, model etc. Earlier today the filter was not working but the Paginator was, but now, the filter is working and the paginator is not. I've been stuck on this the whole day and I don't know what else to do.
This is my code:
views.py
def posts(request):
cars = Userpost.objects.all()
myFilter = UserpostFilter(request.GET, queryset=cars)
cars = myFilter.qs
p = Paginator(Userpost.objects.all(), 2)
page = request.GET.get('page')
cars_list = p.get_page(page)
nums = "a" * cars_list.paginator.num_pages
context = {'cars':cars, "myFilter":myFilter, 'cars_list':cars_list, "nums":nums}
return render(request, 'store/userposts.html', context)
userposts.html
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<div class = 'row'>
<div class = 'col'>
<div class = 'card card-body'>
<form method="get">
{{myFilter.form}}
<button class="btn btn-primary" type = "submit">Search</button>
</form>
</div>
</div>
</div>
<div class="row">
{% for car in cars %}
<div class="col-lg-4">
<img class="thumbnail" src="{{car.imageURL|default:'/images/transparentLogo.png'}}">
<div class="box-element product">
<h6><strong>{{car.Year}} {{car.Make}} {{car.Model}}</strong></h6>
<hr>
<a class="btn btn-outline-success" href="{% url 'post_detail' car.pk %}">View</a>
<h4 style="display: inline-block; float: right"><strong>${{car.Price|floatformat:2}}</strong></h4>
</div>
</div>
{% endfor %}
</div>
<nav aria-label="Page navigation"> <ul class="pagination">
{% if cars_list.has_previous %}
<li class="page-item">
<a class="page-link" href="?page=1" aria-label="Previous">
<span aria-hidden="true">«</span>
<span class="sr-only">begin</span>
</a>
</li> {% endif %}
{% for n in cars_list.paginator.page_range %}
{% if cars_list.number == n %}
<li class="page-item active">
<span class="page-link">{{ n }}<span class="sr-only">(current)</span></span>
</li>
{% elif n > cars_list.number|add:'-3' and n < cars_list.number|add:'3' %}
<li class="page-item"><a class="page-link" href="?page={{ n }}">{{ n }}</a></li>
{% endif %}
{% endfor %}
{% if cars_list.has_next %}
<li class="page-item">
<a class="page-link" href="?page={{ cars_list.paginator.num_pages }}" aria-label="Next">
<span aria-hidden="true">»</span>
<span class="sr-only">end</span>
</a>
</li>
{% endif %} </ul> </nav>
<br/>
{% endblock content %}
filters.py
class UserpostFilter(django_filters.FilterSet):
start_date = DateFilter(field_name = "date_published", lookup_expr = 'gte')
end_date = DateFilter(field_name = "date_published", lookup_expr = 'lte')
min_price = django_filters.NumberFilter(field_name="Price", lookup_expr='gte')
max_price = django_filters.NumberFilter(field_name="Price", lookup_expr='lte')
class Meta:
model = Userpost
field = '__all__'
exclude = 'image', 'user', 'Price', 'Email', 'date_published'
I noticed that when i change the for loop on userposts.html to do "for car in cars_list", the pagination works but it breaks the filter, and using "for car in cars" makes the filter works but the pagination breaks.
I don't know what to do about it and I would really appreciate some help
try this
def posts(request):
cars = Userpost.objects.all()
myFilter = UserpostFilter(request.GET, queryset=cars)
if myFilter.qs:
cars = myFilter.qs
paginator = Paginator(cars, 2)
page = request.GET.get('page')
try:
cars = paginator.page(page)
except PageNotAnInteger:
cars = paginator.page(1)
except EmptyPage:
cars = paginator.page(paginator.num_pages)
context = {'cars_list':cars, "myFilter":myFilter}
return render(request, 'store/userposts.html', context)
template
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<div class = 'row'>
<div class = 'col'>
<div class = 'card card-body'>
<form method="get">
{{myFilter.form}}
<button class="btn btn-primary" type = "submit">Search</button>
</form>
</div>
</div>
</div>
<div class="row">
{% for car in cars_list %}
<div class="col-lg-4">
<img class="thumbnail" src="{{car.imageURL|default:'/images/transparentLogo.png'}}">
<div class="box-element product">
<h6><strong>{{car.Year}} {{car.Make}} {{car.Model}}</strong></h6>
<hr>
<a class="btn btn-outline-success" href="{% url 'post_detail' car.pk %}">View</a>
<h4 style="display: inline-block; float: right"><strong>${{car.Price|floatformat:2}}</strong></h4>
</div>
</div>
{% endfor %}
</div>
<nav aria-label="Page navigation"> <ul class="pagination">
{% if cars_list.has_previous %}
<li class="page-item">
<a class="page-link" href="?page=1" aria-label="Previous">
<span aria-hidden="true">«</span>
<span class="sr-only">begin</span>
</a>
</li> {% endif %}
{% for n in cars_list.paginator.page_range %}
{% if cars_list.number == n %}
<li class="page-item active">
<span class="page-link">{{ n }}<span class="sr-only">(current)</span></span>
</li>
{% elif n > cars_list.number|add:'-3' and n < cars_list.number|add:'3' %}
<li class="page-item"><a class="page-link" href="?page={{ n }}">{{ n }}</a></li>
{% endif %}
{% endfor %}
{% if cars_list.has_next %}
<li class="page-item">
<a class="page-link" href="?page={{ cars_list.paginator.num_pages }}" aria-label="Next">
<span aria-hidden="true">»</span>
<span class="sr-only">end</span>
</a>
</li>
{% endif %} </ul> </nav>
<br/>
{% endblock content %}

Getting a reverse match Django issue

I'm getting a NoReverseMatch error:
NoReverseMatch at /
Reverse for 'post-detail' with arguments '(22, '')' not found. 1 pattern(s) tried: ['post/(?P[0-9]+)/(?P[-a-zA-Z0-9_]+)/$']
not sure how to fix this, here is some of the code :
urls.py
urlpatterns=[
path('', PostListView.as_view(), name='home'),
path('post/new/<slug:slug>/', views.create_post, name='post-create'),
path('post/<int:pk>/<slug:slug>/', views.post_detail, name='post-detail'),
path('like/<slug:slug>/', views.like, name='post-like'),
path('post/<int:pk>/<slug:slug>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/<slug:slug>/delete/', views.post_delete, name='post-delete'),
path('search_posts/', views.search_posts, name='search_posts'),
feed models
models.py
class Post(models.Model):
description = models.TextField(max_length=255)
pic = models.ImageField(upload_to='path/to/img', blank=True)
date_posted = models.DateTimeField(default=timezone.now)
user_name = models.ForeignKey(User, on_delete=models.CASCADE)
tags = models.CharField(max_length=100, blank=True)
def __str__(self):
return self.description
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk, 'slug': self.user_name.profile.slug})
users models
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.png', upload_to='profile_pics')
slug = AutoSlugField(populate_from='user')
bio = models.CharField(max_length=255, blank=True)
friends = models.ManyToManyField('Profile', blank=True)
def __str__(self):
return str(self.user.username)
def get_absolute_url(self):
return "/users/{}".format(self.slug)
views.py
#login_required
def post_detail(request, pk, slug):
post = get_object_or_404(Post, pk=pk)
user = request.user
is_liked = Like.objects.filter(user=user, post=post)
if request.method == 'POST':
form = NewCommentForm(request.POST)
if form.is_valid():
data = form.save(commit=False)
data.post = post
data.username = user
data.save()
return redirect('post-detail', pk=pk, slug=slug)
else:
form = NewCommentForm()
return render(request, 'feed/post_detail.html', {'post':post, 'is_liked':is_liked, 'form':form})
home.html
{% extends "feed/layout.html" %}
{% load static %}
{% block cssfiles %}
{% endblock cssfiles %}
{% block searchform %}
<div class="container2">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css"
integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
<form class="searchbar" action="{% url 'search_posts' %}" method="get"">
<input class="postquery" name="p" type="text" autocomplete="off"/ placeholder="Search posts..">
<button id="search_btn" type="submit">
<i class="fa fa-search"></i>
</button>
</form>
</div>
{% endblock searchform %}
{% block content %}
<div class="container mt-7">
<div class="row">
<div class="col-xl-9 col-md-10 m-auto order-xl-2 mb-5 mb-xl-0">
{% for post in posts %}
<div class="card card-signin my-5">
<div class="card-body">
<img src="{{ post.user_name.profile.image.url }}" class="rounded-circle" width="30" height="30" alt="">
<a class="text-dark" href="{{ post.user_name.profile.get_absolute_url }}"><b>{{ post.user_name }}</b></a>
<br><small class="text-muted">Posted on {{ post.date_posted }}</small>
<br><br>
<p class="card-text text-dark">{{ post.description }}</p>
</div>
{% if post.pic %}
<img class="card-img-top" src="{{ post.pic.url }}" alt="">
{% endif %}
{% if post.tags %}
<br>
<p class="text-danger ml-3"><b>Tags: <i>{{ post.tags }}</i></b></p>
{% endif %}
<div class="card-footer">
<button class="btn btn-white mr-3 like" id="{{ post.id }}">
{% if post in liked_post %}
Unlike | {{post.likes.count}}
{% else %}
Like | {{post.likes.count}}
{% endif %}
</button>
<a class="btn btn-outline-info" href="{% url 'post-detail' post.id user.profile.slug %}">Comments | {{ post.details.count }}</a>
{% if post.user_name == user %}
<a class="btn btn-outline-info mr-0 float-right" href="{% url 'post-update' post.id user.profile.slug %}">Edit Post</a>
<a class="post_delete" href="{% url 'post-delete' post.id user.profile.slug %}">delete</a>
{% endif %}
</div>
</div>
{% endfor %}
</div>
</div>
</div>
{% 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 content %}
When i click on the home page link I get the error mentioned above , not sure what in this template is causing it ? any ideas ?

Is there any way I can pass a filtered query set into Django's pagination?

view.py
def quiz(request):
question_topic = request.POST.getlist("topic_checkbox") # Retrieves list of topics selected by user
question_list = Quiz.objects.filter(Topic_name__in = question_topic) #filters out questions by topics
paginator = Paginator(question_list,1) # when i pass all the objects rather than the filtered query set it seems to work but when i paginate with the filtered queryset only the first page loads
page = request.GET.get('page')
try:
question_list = paginator.page(page)
except PageNotAnInteger:
question_list = paginator.page(1)
except EmptyPage:
question_list = paginator.page(paginator.num_pages)
return render(request,"Quiz/quiz_home.html",{"question_list":question_list})
quiz_home.html
{% block content %}
{% for q in question_list %} # loops through the filtered queryset
{% if question_list.has_next %}
<h3>Question {{q.id}}</h3>
<form method="POST" action="?page={{ question_list.next_page_number }}">{% csrf_token %}
# The form should enable me to gather the users input whilst simultaneoulsy going to the next question in the for loop. But when question sumbitted the next page is blank showing no contents
{% if q.picture %}
<img src="/media/{{q.picture}}"> <br>
{% endif %}
{{q.id}}.) </label><label id="question_text">{{q.question}}</label><br>
<input type="hidden" id= "q_id" name="q_id" value="{{q.id}}">
<input type="hidden" id= "topic" name="topic" value="{{q.topic}}">
<input type="radio" id="opt1" name="options" value="{{q.option1}}" required>{{ q.option1 }}<br>
<input type="radio" id="opt2" name="options" value="{{q.option2}}" required>{{ q.option2 }}<br>
<input type="radio" id="opt3" name="options" value="{{q.option3}}" required>{{ q.option3 }}<br>
<hr>
<input type="submit" id="mybtn" value="Submit"> #once clicked it should paginate to next page
</form>
{% else %}
<hr>
<form action="/home/">{% csrf_token %}
<input type="submit" name="End" value="End">
</form>
{% endif %}
{% endfor %}
{% endblock %}
Essentially im trying to filter out questions based on what topics the user has selected. This queryset of questions is then paginated so that each page shows one question.
I'll show you a pagination instance:
views.py
class CategoryDetail(ListView):
model = Task
template_name = 'category/category_detail.html'
context_object_name = 'task'
paginate_by = 5
def get_queryset(self):
self.category = get_object_or_404(Category,
pk=self.kwargs['pk'])
return Task.objects.filter(category=self.category).order_by('-id')
def get_context_data(self, *, object_list=None, **kwargs):
context = super(CategoryDetail, self).get_context_data(**kwargs)
self.category = get_object_or_404(Category, pk=self.kwargs['pk'])
# context['category'] = self.category
return context
category/category_detail.html
....
<div class="card-footer py-4">
{% if is_paginated %}
<nav aria-label="...">
<ul class="pagination justify-content-end mb-0">
{% if page_obj.has_previous %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.previous_page_number }}" tabindex="-1">
<i class="fas fa-angle-left"></i>
<span class="sr-only">Previous</span>
</a>
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link" href="#" tabindex="-1">
<i class="fas fa-angle-left"></i>
<span class="sr-only">Previous</span>
</a>
</li>
{% endif %}
{% for i in paginator.page_range %}
{% if page_obj.number == i %}
<li class="page-item active">
<a class="page-link" href="#"> {{ i }} </a>
</li>
{% else %}
<li class="page-item">
<a class="page-link" href="?page={{ i }}">{{ i }}<span class="sr-only">(current)</span></a>
</li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.next_page_number }}">
<i class="fas fa-angle-right"></i>
<span class="sr-only">Next</span>
</a>
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link" href="#">
<i class="fas fa-angle-right"></i>
<span class="sr-only">Next</span>
</a>
</li>
{% endif %}
</ul>
</nav>
{% endif %}
</div>
Django already has a ready-made paging structure. You can use it in your Html file you want to use.

why when I click a different user returns me back to the current request user?

sorry, I had to take some screenshots to explains what is going on with me. now, I have much profile that has many different users and when I log in with one of it I'll assume the username is: medoabdin like you find on the screenshot now (medoabdin) and the name of it is (Origin) for me is a current user request. so, now I have also many different questions created by the different users, and when I want to enter any other profile let's suppose the user is (abdelhamedabdin) by current request user it returns me back to the current request (medoabdin) and not returns me back to abdelhamedabdin.
however, when I check the link URL I find the link is correct and when I log in with (abdelhamedabdin) user I see the same thing occurs to me against (medoabdin) so, can anyone tell me what is going on guys?
these are screenshots:
current request (medoabdin),
several questions,
show the link url for different users,
accounts/profile.html
{% extends 'base.html' %}
{% block title %} {{ user.first_name }} {{ user.last_name }} Profile {% endblock %}
{% block body %}
<!-- User Profile Section -->
{% if user.is_authenticated %}
<div class="profile">
<div class="container-fluid">
<div class="col-md-1">
<div class="thumbnail">
<div class="row">
<div class="col-xs-12">
<!-- Profile View Section -->
<div class="logo-image text-center">
{% if user.userprofile.logo %}
<div class="my-image">
{% if request.user.username == user.userprofile.slug %}
<a href="{% url 'accounts:user_image' user.userprofile.slug %}">
<img class="img-responsive" src="{{ user.userprofile.logo.url }}">
</a>
<span>
<a href="{% url 'accounts:add_avatar' user.userprofile.slug %}" class="fa fa-camera fa-1x text-center">
<p>Upload Image</p>
</a>
</span>
{% endif %}
</div>
{% else %}
{% load static %}
<div class="my-image">
<img class="img-responsive img-thumbnail" src="{% static 'index/images/default-logo.jpg' %}">
<span>
<a href="{% url 'accounts:add_avatar' user.userprofile.slug %}" class="fa fa-camera fa-1x text-center">
<p>Upload Image</p>
</a>
</span>
</div>
{% endif %}
{% if user.first_name != '' and user.last_name != '' %}
<h4>{{ user.first_name }} {{ user.last_name }}</h4>
{% else %}
<h4>User Profile</h4>
{% endif %}
</div>
</div>
<div class="col-xs-12">
<div class="caption">
<ul class="nav nav-pills nav-stacked">
<li role="presentation" class="active">Overview</li>
<li role="presentation" class="">Personal Information</li>
<li role="presentation" class="">Skills</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!-- Information Sections -->
<div class="col-md-8 col-md-offset-3 information">
<div class="overview show" id="overview">
<h2 class="line">Overview</h2>
<p class="lead">{{ user.userprofile.overview }}</p>
<a data-placement="bottom" title="update overview" class="fa fa-edit" data-toggle="modal" data-tooltip="tooltip" data-target=".overview_info"></a>
</div>
<div class="personal-info" id="personal-information">
<h2 class="line">Personal Information</h2>
<p class="lead">City: {{ user.userprofile.city }}</p>
<p class="lead">Phone Number: 0{{ user.userprofile.phone }}</p>
<p class="lead">Sex: {{ user.userprofile.sex }}</p>
<a data-placement="bottom" title="update personal information" class="fa fa-edit" data-toggle="modal" data-tooltip="tooltip" data-target=".personal_info"></a>
</div>
<div class="skill" id="my-skills">
<h2 class="line">Skills:</h2>
<p class="lead">{{ user.userprofile.skill }}</p>
<a data-placement="bottom" title="update skills" class="fa fa-edit" data-toggle="modal" data-tooltip="tooltip" data-target=".skills"></a>
</div>
</div>
<!-- get all questions -->
{% if user_prof.userasking_set.all %}
<div class="col-md-8 col-md-offset-3 user_questions">
<h2 class="line">All Questions You Asked</h2>
{% for questions in user_prof.userasking_set.all %}
<p>{{ questions.title }}</p>
{% endfor %}
</div>
{% endif %}
<!-- get favourites -->
{% if get_favourite %}
<div class="col-md-8 col-md-offset-3 user_questions">
<h2 class="line">Favourites</h2>
{% for fav in get_favourite %}
<p>{{ fav.title }}</p>
{% endfor %}
</div>
{% endif %}
</div>
{% include 'accounts/information_form.html' %}
</div>
{% include 'base_footer.html' %}
{% endif %}
{% endblock %}
accounts/views.py
#method_decorator(login_required, name='dispatch')
# view profile page
class ViewProfile(UpdateView):
queryset = UserProfile.objects.all()
template_name = 'accounts/profile.html'
form_class = UpdateInfoForm
slug_field = 'slug'
slug_url_kwarg = 'user_slug'
def get_success_url(self):
return reverse_lazy('accounts:view_profile', kwargs={'user_slug': self.request.user.userprofile.slug})
def get_context_data(self, **kwargs):
self.request.session['switch_comment'] = False
context = super().get_context_data(**kwargs)
user_prof = UserProfile.objects.get(user=self.request.user)
context['user_prof'] = user_prof
context['get_favourite'] = User.objects.get(username=self.request.user.username).favorite.all()
return context
def form_valid(self, form):
form.instance.user_slug = self.request.user.userprofile.slug
self.object = form.save()
return super().form_valid(form)
community/views.py
# List all questions + search
class UserQuestions(ListView):
template_name = 'community/user_questions.html'
context_object_name = 'all_objects'
queryset = UserAsking
def get_context_data(self, object_list=queryset, **kwargs):
context = super().get_context_data(**kwargs)
# paginator
context['all_objects'] = UserAsking.objects.all()
paginator = Paginator(context['all_objects'], 5)
page_number = self.request.GET.get('page_number')
context['all_objects'] = paginator.get_page(page_number)
# search
context['query'] = self.request.GET.get("query", '')
if context['query']:
all_objects = UserAsking.objects.all().order_by('-date')
context['all_objects'] = all_objects.filter(
Q(title__contains=self.request.GET['query']) |
Q(question__contains=self.request.GET['query']) |
Q(field__contains=self.request.GET['query'])
)
return context
community/user_questions.py
{% extends 'base.html' %}
{% block title %} All Questions That People Asked {% endblock %}
{% block body %}
{% if request.user.is_authenticated %}
<div class="all-questions">
<div class="container">
<div class="fl-left hidden-sm hidden-xs">
<h2>All Questions</h2>
</div>
<div class="fl-right hidden-sm hidden-xs">
Ask Question
</div>
<div class="clear"></div>
<div class="row">
<div class="add-q">
<div class="col-sm-12 visible-sm-block visible-xs-block">
<h2>All Questions</h2>
</div>
<div class="col-sm-12 visible-sm-block visible-xs-block">
Ask Question
</div>
</div>
{% if all_objects %}
<div class="col-sm-12">
<div class="questions">
{% for post in all_objects %}
<div class="q_section">
<a class="text-primary title" href="{% url 'community:question_view' post.ask_slug %}">{{ post.title }}</a>
<p class="field">{{ post.field }}</p>
<div class="info fl-right">
<span class="time">{{ post.date }}</span> |
<a href="{% url 'accounts:view_profile' post.userprofile.slug %}" style="font-size:14px">
{% if post.userprofile.user.first_name != '' %}
{{ post.userprofile.user.first_name }}
{% else %}
User
{% endif %}
<img class="logo-image" style="width:25px;height: 25px" src="
{% if request.user.userprofile.logo %}
{{ request.user.userprofile.logo.url }}
{% else %}
{% load static %}
{% static 'index/images/default-logo.jpg' %}
{% endif %}
">
</a>
</div>
<div class="">
<!--a class="btn btn-primary btn-lg" href="{# {% url 'community:delete_post' post.id %} #}">
<i class="fa fa-trash x2"></i>
</a-->
</div>
</div>
{% endfor %}
</div>
</div>
{% else %}
<h2 class="text-center text-info">No Questions</h2>
{% endif %}
</div>
<!-- Pagination -->
{% if all_objects %}
<div class="pagination">
<span class="step-links">
{% if all_objects.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ all_objects.number }} of {{ all_objects.paginator.num_pages }}.
</span>
{% if all_objects.has_next %}
next
last »
{% endif %}
</span>
</div>
{% endif %}
</div>
</div>
{% include 'base_footer.html' %}
{% endif %}
{% endblock %}