Django template tags conditionals - django

Right, am struggling with my blog app when trying to render some logic through the template view. So the idea is to render a one time only button for the newly authenticated users that do not have a post published and after the user has published its first post the button will be rendered within a for loop so he/she'll be able to create/delete a new one from there.
views.py
#login_required(login_url='app_users:login')
#allowed_users(allowed_roles=['admin', 'staff', 'users'])
def blog(request):
posts = BlogPost.objects.all().order_by('date_posted')
context = {'title': 'Blog', 'posts': posts}
return render(request, 'app_blog/blog.html', context)
models.py
class BlogPost(models.Model):
title = models.CharField(max_length=100, null=True)
content = models.TextField(null=True)
date_posted = models.DateTimeField(default=timezone.now, null=True, blank=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
blog.html
{% block content %}
{% if request.user not in posts|last %}
<div class="container" style="float: left;">
<a class="btn btn-primary btn-sm mt-1 mb-1" href="{% url 'app_blog:blog_create' user.id %}"><h5>C'mon {{ request.user.username }}, don't be shy! Create Your First Blog Post!</h5></a>
</div>
{% endif %}
<br>
<br>
{% for post in posts %}
<br>
<div class="container">
<article class="media content-section">
<img class="rounded-circle account-img" src="{{ post.author.profile.image.url }}" alt="Image could not be uploaded!">
<div class="card-body media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'app_blog:blog_user_detail' post.id %}">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted|date:"d F Y" }}</small>
</div>
<div class="article-metadata">
{% if post.author == request.user %}
<div>
<a class="btn btn-primary btn-sm mt-1 mb-1" href="{% url 'app_blog:blog_create' post.id %}">Create New Post</a>
<a class="btn btn-primary btn-danger btn-sm mt-1 mb-1" href="{% url 'app_blog:blog_delete' post.id %}">Delete</a>
</div>
{% endif %}
</div>
<h2><a class="article-title" href="{% url 'app_blog:blog_detail' post.id %}">{{ post.title }}</a></h2>
<p class="article-content">{{ post.content|safe }}</p>
</div>
</article>
</div>
<br>
{% endfor %}
{% endblock %}
So, again, end question would be about what sort of conditionals to use here:
{% if request.user not in posts|last %}
Thanks.

Not quite sure I fully understand but I will suggest something. A user who was a saved post should not see that button? If so, maybe something like this would work:
{% if request.user not in posts.authors.all %}
EDIT original solution won't work. posts is a queryset object
views.py
#login_required(login_url='app_users:login')
#allowed_users(allowed_roles=['admin', 'staff', 'users'])
def blog(request):
posts = BlogPost.objects.all().order_by('date_posted')
new_user = len(posts.filter(author=request.user)) == 0
context = {'title': 'Blog', 'posts': posts, 'new_user': new_user}
return render(request, 'app_blog/blog.html', context)
blog.html (just the condition)
{% if new_user %}

Related

DJango, the preivous post or the next post according to that category list

I am studying to develope a blog website using DJango's generic view class.
I categorized blogs into categories.
If you select a blog from the full list and go to the detail page, you have implemented the ability to go to the previous post and the next post using "previous()" and "next()" in that post.
I want to select a blog from a category list and move it to the preivous post or the next post according to that category list, but I don't know how.
What can I do?
models.py
class Post(models.Model):
..........
def prev(self):
return self.get_previous_by_created_at()
def next(self):
return self.get_next_by_created_at()
views.py
class PostListByCategory(PostList):
def get_queryset(self):
slug = self.kwargs['slug']
if slug == 'no_category':
category = None
else:
category = Category.objects.get(slug=slug)
return Post.objects.filter(category=category).order_by('-pk')
def get_context_data(self, **kwargs):
context = super(PostListByCategory, self).get_context_data()
slug = self.kwargs['slug']
if slug == 'no_category':
category = 'None'
else:
category = Category.objects.get(slug=slug)
context['category'] = category
return context
post_detail.html
..............
<div class="row row-cols-auto">
{% if object.next %}
<div class="col">
<a href="{% url 'tube_detail' object.next.pk %}" class="btn btn-sm pt-1 pb-1 bg-light" title="Prev">
<i class="bi bi-caret-left-fill" style="color:#dd3535"></i>
</a>
</div>
{% endif %}
<div class="col">
<a href="{% url 'tube_list' %}{% if request.GET.category %}category/{{ request.GET.category}}{% endif %}" class="btn btn-sm pt-1 pb-1 bg-light" title="LIST">
<i class="bi bi-list" style="color:#dd3535"></i>
</a>
</div>
{% if object.prev %}
<div class="col">
<a href="{% url 'tube_detail' object.prev.pk %}" class="btn btn-sm pt-1 pb-1 bg-light" title="Next">
<i class="bi bi-caret-right-fill" style="color:#dd3535"></i>
</a>
</div>
{% endif %}
</div>
''''''''''''

Django error NoReverseMatch at / Reverse for 'add-to-fav-songs' with arguments '('',)' not found

So I want users to be able to add songs to a section called 'Favorite songs'(just like adding products to a cart in an e-commerce website) but I'm getting this error NoReverseMatch at / Reverse for 'add-to-fav-songs' with arguments '('',)' not found. 1 pattern(s) tried: ['add\\-to\\-fav\\-songs/(?P<pk>[0-9]+)/$']. Can anyone correct my code and show me how can I add songs to favorite songs.
Thanks in advance!
My models.py:
class Songs(models.Model):
title = models.CharField(max_length = 100)
lyrics = models.TextField()
author = models.CharField(max_length = 100)
track_image = models.CharField(max_length=2083)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('/', kwargs={'pk': self.pk})
My views.py:
def home(request):
context = {
'songs': Songs.objects.all()
}
return render(request, 'home.html', context)
#login_required
def add_to_fav_songs(request):
fav_song = get_object_or_404(Songs)
class Fav_songs(ListView):
model = Songs
template_name = 'fav_songs.html'
context_object_name = 'fav_song'
paginate_by = 2
def get_queryset(self):
return Songs.objects.filter(id=self.kwargs.get('pk'))
My urls.py:
path('add-to-fav-songs/<int:pk>/', views.add_to_fav_songs, name='add-to-fav-songs'),
path('favourite-songs/', Fav_songs.as_view(), name='favourite-songs'),
My home.html:
{% for song in songs %}
<article class="media content-section">
<div class="media-body">
<h2><a class="article-title" href="{% url 'song-detail' song.id %}">{{ song.title }}</a></h2>
<div class="article-metadata">
<a class="mr-2" href="{% url 'author-songs' song.author %}">{{ song.author }}</a>
</div>
<br>
<img class="card-img-bottom" height="339px" width="20px" src="{{ song.track_image }}">
</div>
<!-- <button> Add To Favourite Songs</button> -->
<form class="form" method="POST" action="{% url 'add-to-fav-songs' song.id %}">
{% csrf_token %}
<div class="action">
<button class="like btn btn-danger" type="button"><span class="fa fa-heart"></span></button>
</div>
</form>
</article>
{% endfor %}
My fav_songs.html:
{% for fav_song in songs %}
<article class="media content-section">
<div class="media-body">
<h2><a class="article-title" href="{% url 'song-detail' song.id %}">{{ fav_song.title }}</a></h2>
<div class="article-metadata">
<a class="mr-2" href="{% url 'author-songs' song.author %}">{{ fav_song.author }}</a>
</div>
<br>
<img class="card-img-bottom" height="339px" width="20px" src="{{ fav_song.track_image }}">
</div>
</article>
{% endfor %}
The first issue in your code was that you wrote:
{% url 'add-to-fav-songs' object.id %}
Here the problem is that there is no variable object in the context and hence object.id just resolves to an empty string, giving you an error. You need to replace this with song.id:
{% url 'add-to-fav-songs' song.id %}
Next you tried this comment to remove that faulty code:
<!-- <button> Add To Favourite Songs</button> -->
Here the problem is that Django does not care about HTML comments, it will try to render them and once again give you the same error. You can either remove this code or use the comment template tag [Django docs] to make Django actually consider it as a comment:
{% comment %}
<button> Add To Favourite Songs</button>
{% endcomment %}

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 ?

Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P<pk>[^/]+)/$']

I'm getting this error when I use
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
but there is no such error when path is..
path('create_order', views.createOrder, name="create_order"),
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('products/', views.products, name='products'),
path('customer/<str:pk_test>/', views.customer, name="customer"),
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
path('update_order/<str:pk>/', views.updateOrder, name="update_order"),
path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"),
]
views.py
def createOrder(request, pk):
OrderFormSet = inlineformset_factory(Customer, Order , fields=('product','status'), extra=9)
customer = Customer.objects.get(id=pk)
formset = OrderFormSet(queryset=Order.objects.none(), instance=customer)
#form = OrderForm(initial={'customer':customer})
if request.method == 'POST':
#print('printing post', request.POST)
formset = OrderFormSet(request.POST, instance=customer)
if formset.is_valid():
formset.save()
return redirect('/')
context = {'formset': formset}
#return redirect('accounts/order_form.html', context)
return render(request, 'accounts/order_form.html', context)
i also have tried redirect, that's not working the problem is with urls.py.
customer.html
{% extends 'accounts/main.html' %}
{% block content %}
<br>
<div class="row">
<div class="col-md">
<div class="card card-body">
<h5>Customer:</h5>
<hr>
<a class="btn btn-outline-info btn-sm btn-block" href="">Update Customer</a>
<a class="btn btn-outline-info btn-sm btn-block" href="{% url 'create_order' customer.id %}">Place Order</a>
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Contact Information</h5>
<hr>
<p>Email: {{customer.email}}</p>
<p>Phone: {{customer.phone}}</p>
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Total Order</h5>
<hr>
<h1 style="text-align: center;padding: 10px;">{{order_count}}</h1>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col">
<div class="card card-body">
<form method="POST">
<button class="btn btn-primary" type="submit">Search</button>
</form>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md">
<div class="card card-body">
<table class="table table-sm">
<tr>
<th>Product</th>
<th>Category</th>
<th>Date Ordered</th>
<th>Status</th>
<th>Update</th>
<th>Remove</th>
</tr>
{% for order in orders %}
<tr>
<td>{{order.product}}</td>
<td>{{order.product.category}}</td>
<td>{{order.date_created}}</td>
<td>{{order.status}}</td>
<td><a class="btn btn-outline-info btn-md " href="{% url 'update_order' order.id %}">Update</a></td>
<td><a class="btn btn-outline-danger btn-md " href="{% url 'delete_order' order.id %}">Delete</a></td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock %}
models.py
class Customer(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
phone = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-md-6">
<div class="card card-body">
<form action="" method="POST">
{% csrf_token %}
{{formset.managment_form}} <!-- to remove the managmentForm data missing or has been tempered wiith , error -->
{% for form in formset %}
{{formset}} <!--in context of views.py -->
<hr>
{% endfor %}
<input class="btn btn-outline-success btn-md" type="submit" name="submit">
</form>
</div>
</div>
</div>
{% endblock %}
I have added the templates , and thanks to all but I think the only problem is with urls.py , because if I use
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
instead of
path('create_order', views.createOrder, name="create_order"),
then I get error, otherwise there is no such error for the above path.
I finally got the error.
So, error was here
the href which we have used id {% url 'create_order' customer.id %}
and this is in customer.html ,so the customer.id will get value provided by the views.customer
but if you see in your view.customer,
context = {'customers':customers,'orders': orders,'orders_count': orders_count}
because we followed a tutorial video, that guy did some changes which we didn't because it isn't shown in the video.
the changes he did was that
he changed 'customers' to 'customer' and now context of customer.html is good
because now it knows what the hell is customer.id
i know where the problem is
in the dashboard.html you should delete the line includes {% url 'create_order' %}
I don't know what is the problem but just replaced the file urls.py from GitHub with the same context and it's not showing that error.
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('products/', views.products, name='products'),
path('customer/<str:pk_test>/', views.customer, name="customer"),
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
path('update_order/<str:pk>/', views.updateOrder, name="update_order"),
path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"),
]
views.py
from django.forms import inlineformset_factory
def createOrder(request, pk):
OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status'), extra=10 )
customer = Customer.objects.get(id=pk)
formset = OrderFormSet(queryset=Order.objects.none(),instance=customer)
#form = OrderForm(initial={'customer':customer})
if request.method == 'POST':
#print('Printing POST:', request.POST)
#form = OrderForm(request.POST)
formset = OrderFormSet(request.POST, instance=customer)
if formset.is_valid():
formset.save()
return redirect('/')
context = {'form':formset}
return render(request, 'accounts/order_form.html', context)
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-md-6">
<div class="card card-body">
<form action="" method="POST">
{% csrf_token %}
{{ form.management_form }}
{% for field in form %}
{{field}}
<hr>
{% endfor %}
<input type="submit" name="Submit">
</form>
</div>
</div>
</div>
{% endblock %}
Again I don't know why it was showing this error and where was the problem but just relapced it with the same code from GitHub and it worked.if someone know how it worked, that will be really helpful in near future.
in dashboard you should remove the line with create order
cause there is use of create_order url without id so there's an error

how can I access userprofile from another user?

I need some help when I create a user and user profile accordingly and when I try to access to any user by another user the request turns me on the request I work on not the real user, although, I'm using the slug to specify what the user I click on it maybe I can not explain what happens to me exactly for more explanation, please click on that video to show what I mean: https://www.youtube.com/watch?v=MzSo0ay2_Xk&feature=youtu.be
accounts app
models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.template.defaultfilters import slugify
CHOICE = [('male', 'male'), ('female', 'female')]
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
slug = models.SlugField(max_length=100, unique=True, blank=True)
overview = models.TextField(editable=True, blank=True, default='You have no an Overview yet')
city = models.CharField(max_length=20, blank=False)
phone = models.IntegerField(default=0, blank=True)
sex = models.CharField(max_length=10, default='male', choices=CHOICE)
skill = models.CharField(max_length=100, default='You have no skills yet')
logo = models.ImageField(upload_to='images/', default='images/default-logo.jpg', blank=True)
def __str__(self):
return self.user.username
def save(self, *args, **kwargs):
self.slug = slugify(self.user)
super().save(*args, **kwargs)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user=kwargs['instance'])
post_save.connect(receiver=create_profile, sender=User)
view.py
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):
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)
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 %}
<h4>{{ user.first_name }} {{ user.last_name }}</h4>
</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 %}
self.request.user refers to the currently logged in user. That is why you are getting the same result for all users.
To get what you want, you need to make the following change in your views:
user_prof = UserProfile.objects.get(pk=self.kwargs['pk'])
But also, I'm not sure why you are using an UpdateView when you simply want to display objects? You should use TemplateView instead.