i am building a website like instagram where users can follow friends, i have been able to implement follow friend and also displaying friends of friends (mutual friend). I was not able to get the count of friends of friends; this is what i tried:
Model:
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True)
friends = models.ManyToManyField('Profile', related_name="my_friends",blank=True)
view:
#login_required
def profile_user_view(request, username):
#Friend of Friends
p = Profile.objects.filter(user__username=username).order_by('-id')
all_friends = request.user.profile.friends.values_list('pk', flat=True)
friends_of_friend = Profile.objects.filter(pk__in=all_friends)
context = {
'profile_img': p,
'friends_of_friend': friends_of_friend,
}
return render(...)
Template:
{% for data in profile_img %}
{% for friend in friends_of_friend %}
{% if friend in data.friends.all %}
<li>
<a href="{% url 'site:profile-view' friend.user.username %}" class="dark-grey-text">
<b>{{ friend.user.username|lower }}</b>
</a>
</li>
<li>
{{ friend.count }} #This is not showing the count of friends of friends, when i use length it displays '0 0' instead of '2' (mutual friends)
</li>
{% endif %}
{% endfor %}
{% endfor %}
You need to use friends_of_friend.count to get count of current user's friends. If you want every friend's friend count then use {{ friend.friends.count }}.
Honestly, you do not need this much context in template. You can access them all from {{ user }} attribute in template. For example:
{% for friend in user.friends.all %}
Username {{ friend.user.username | lower }}
Count {{ friend.friends.count }}
{% endfor %}
i know it is late but ....
utils.py:
from django.contrib.auth.models import User
from collections import Counter
#this function finds friends_of_friends_id
def friendship(user):
a = User.objects.get(id=user)
return [i.id for i in a.profile.friends.all()]
#this function will take return all your friends's id with how many mitual_friend you have together
def count_mitual_friends(user_id):
return Counter([foaf_id for friend_id in friendship(user_id)
for foaf_id in friendship(friend_id)
if foaf_id != user_id
and foaf_id not in friendship(user_id)
])
Related
I am trying to add the profile image of each user(designer) in the below list view
For each designer, there is a profile image that has already been uploaded before I am just trying to get it and show it in the UserPost List View.
Currently, with the below code, the designer image is not showing.
Here is the views.py
class UserPostListView(ListView):
model = Post
template_name = "user_posts.html"
context_object_name = 'posts'
queryset = Post.objects.filter(admin_approved=True)
paginate_by = 6
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get('username'))
return Post.objects.filter(designer=user, admin_approved=True).order_by('-date_posted')
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
has_items = Item.objects.filter(designer__username=self.kwargs['username']).exists()
context['has_items'] = has_items
return context
Here is the template
{% if has_items %}
<h1> Hello, this is {{ view.kwargs.username }} </h1>
--------------------------------------
<img class="profile_image" src={{ designer.profile.image.url }}> <----------- I want it to appear
{% else %}
<h1>Hello, this is {{ view.kwargs.username }} </h1>
--------------------------------------
<img class="profile_image" src={{ designer.profile.image.url }}> <----------- I want it to appear
{% endif %}
Problem
The issue seems to be that your template is missing a for loop to loop through posts so that you can access the respective designer. Also, I'm assuming that view is accessible from a post object as it's not explicitly defined anywhere else in your code example. Lastly, your else loop is doing the same as the if loop.
Solution
Include a for loop in template so that you can access designers' profile image URLs.
{% if has_items %}
{% for post in posts %}
<h1> Hello, this is {{ post.view.kwargs.username }} </h1>
--------------------------------------
<img class="profile_image" src={{ post.designer.profile.image.url }}>
{% endfor %}
{% else %}
...
{% endif %}
References
ListView Documentation https://docs.djangoproject.com/en/3.1/ref/class-based-views/generic-display/#listview
ListView Code https://github.com/django/django/blob/master/django/views/generic/list.py#L194
I'm trying to develop a forum application.
I'm trying to display the latest topic that's been posted in each category on a listing page. However, I realised after adding more than one category that I need a separate query for each single category or it just shows the newest topic overall.
I'm just not sure how to keep my logic in the view for the queries. Obviously, I could just perform the query inside of my for loop but that doesn't seem very MVT oriented.
Here's my views.py:
from django.shortcuts import render
from .models import ForumReply, ForumCategory, ForumTopic
def index(req):
categories = ForumCategory.objects.all()
#find latest topic or topic by reply
topic = ForumTopic.objects.latest('created_at')
reply = ForumReply.objects.latest('created_at')
if (topic.created_at > reply.created_at):
latest = topic
else:
latest = reply.topic
return render(req, "forum/category_listing.html",
{'categories': categories, 'latest': latest})
And my category_listing.html:
{% extends '__base.html' %}
{% block content %}
{% for category in categories %}
<div class="forum_category">
<h1>{{ category.title }}</h1>
{{ category.body }}
<br />
<em>Latest Post: </em> {{ latest.title }} by {{ latest.user }} at {{ latest.created_at|date:"D d F Y h:i" }}
</div>
<br />
{% endfor %}
{% endblock %}
You can create a custom template tag that returns the latest post for each category.
Something like this:
# views.py
def index(req):
categories = ForumCategory.objects.all()
return render(req, "forum/category_listing.html", {'categories': categories})
# templatetags/category_tags.py
#register.assignment_tag
def get_latest_post(category):
# perform logic here for selecting latest post for specific category
return latest
# category_listing.html
{% load category_tags %}
{% for category in categories %}
{% get_latest_post category as latest %}
<em>Latest Post: </em> {{ latest.title }} by {{ latest.user }} at {{ latest.created_at|date:"D d F Y h:i" }}
{% endfor %}
You can read the documentation for more information https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/#assignment-tags
I'm working with flask and have a html page that contains of user name(user.html) which took from table, Now How can I see more detail by clicking on each of users(which route to profile)?
I don't use login for app So I don't want to use g
app.py
# am I doing it right?
#app.route('/profile/<int:id>')
def profile(id=None):
detail = Contacts.query.get(id)
return render_template('profile.html', detail= detail , id=id)
user.html
{% extends "layout.html" %}
{% block content %}
<h2>show user</h2>
{% for contact in contact %}
# I got error when I click on each user name to see their 'profile'
#I guess because of id How can Solve it?
#error BuildError: ('profile', {}, None)
<strong>name:</strong><a href={{url_for('profile')}}>
{{ contact.name}}</a><br>
{% endfor %}
{% endblock %}
profile.html
{% extends "layout.html" %}
{% block content %}
<h2>show user profile</h2>
# how can I make it specific for each row of table(each user)?
{% for detail in Contacts %}
<strong>name:</strong> {{ detail.name}} <br>
<strong>email:</strong> {{ detail.email }} <br>
<strong>age:</strong> {{ detail.age}} <br>
<br>
{% endfor %}
{% endblock %}
model.py
class Contacts(db.Model):
__tablename__ = "Contacts"
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(50))
email = db.Column(db.String(50))
age = db.Column(db.Integer)
submit = SubmitField("Submit")
I noticed two things in your code:
# this
<a href={{url_for('profile')}}>
# should be
<a href={{url_for('profile', id=contact.id)}}>
# otherwise Flask can't find the route, because it needs an id
And the other one:
{% for detail in Contacts %}
There is no such thing as a Contacts variable in your template, because your view function does not send it. Just get rid of the loop and use detail directly, because it's what you sent to the template.
Edited my code: In the custom fieldset of a model admin:
{%load app_extras %}
{% if field.field.name == 'mobile' %}
<a target="hiddenIframe" href="http://url_to_call.php?exten={{request.user.employee_profile.extension}}&phone={{ field.field.value }}">Click-to-call</a>
{% my_mobile mobile=field.field.value as mob %}
{% endif %}
{% if field.field.name == 'sms_message' %}{{ mob }}
<a target="hiddenIframe" href="http://url_for_send_sms.php?sms_message={{ field.field.value }}&phone={{ mob }}">Click-to-send-sms</a>
{% endif %}
Here I am trying to access mobile number as well as sms_message fields of the model admin form simultaneously.
I have figured that I need to use custom tags, so I created the templatetags module, with app_extras.py containiging the function to assign the value of mobile and return it as follows:
#register.assignment_tag
def my_mobile(*args, **kwargs):
m_mobile = int(kwargs['mobile'])
return {'m_mobile': m_mobile }
In the template fiedset.html above note changes: This returns a Long value as: {'m_mobile': 1234534519L}
When seen on the browser for url for hyperlink shows:
http://url_for_send_sms.php/?sms_message=fgdfg&phone={%27m_mobile%27:%1234534519L}
How do I access the mobile number? Is my custom tag correct?
I formatted the output in my tag as:
#register.assignment_tag
def my_mobile(*args, **kwargs):
m_mobile = ("%d" %int(kwargs['mobile']))
return {'m_mobile': m_mobile }
In the template fieldset.html changed the code as:
{% if field.field.name == 'sms_message' %}
<a target="hiddenIframe" href="http://url_for_send_sms.php?sms_message={{ field.field.value }}&phone=={{ mob.m_mobile }}">Click-to-send-sms</a>
{% endif %}
Important: Both the mobile number and the sms_message are in the same line of the fieldset in the django modeladmin (in my case). So above code belongs to the loop {% for line in fieldset %} loop
Try
{% for ln in fieldset %}
{% for fld in ln %}
{% if f.field.name == 'mobile' %}
{{ f.field.value }}
{% endif %}
{% endfor %}
{% endfor %}
Maybe this is not the best solution ... but it is solution :)
Please help me in displaying the values of dictionary in django templates. I tried google to find out, but could not get the solution.
Below is the Model
class Ride(models.Model):
type = models.BooleanField(default=False)
add_source = models.ForeignKey(Address, related_name='source')
add_destination = models.ForeignKey(Address, related_name='destination')
ride_comment = models.TextField(null=True,max_length=140,blank=True)
def __unicode__(self):
return self.ride_comment
class Driver(models.Model):
ride_id = models.ForeignKey(Ride)
user_id = models.ForeignKey(User)
drv_carseats = models.SmallIntegerField(null=True,blank=False)
def __unicode__(self):
return self.user_id.username
View
for ride in result_list:
if ride.type:
driver = Driver.objects.get(ride_id = ride)
userList[ride.pk] = driver.user_id.username
print 'driver', driver.user_id.username, userList[ride.pk]
return render_to_response('rides/search.html', {'result_list':result_list,'userList':userList}, context )
And here is my template code
{% for result in result_list %}
{% if result %}
{{ userList[result.pk] }}
<em>{{ result.add_source }}</em>
<em>{{ result.add_destination }}</em>
<em>{{ result.ride_comment }}</em>
{% endif %}
{% endfor %}
I am getting the following error
TemplateSyntaxError at /rides/search/
Could not parse the remainder: '[result.pk]' from 'userList[result.pk]'
you should write a django custom filter for this.
create a file name get_dict_val.py inside your app..
project
-app
-templatetags
__init__.py
get_dict_val.py
Now in get_dict_val.py
#register.filter
def get_item(dictionary, key):
return dictionary.get(key)
In template
add this as first line write..
{% load get_dict_val %}
now replace in your code in template
{{ userList|get_item:result.pk }}
You don't need to create dictionary to access drivers at the template level, you can follow the relationship backward as Driver model has the foreign key for Ride model:
{% for result in result_list %}
{% if result %}
{% with result.driver_set.all as drivers %}
{% for driver in drivers %}
{{ driver.user_id }}
{% endfor %}
{% endwith %}
<em>{{ result.add_source }}</em>
<em>{{ result.add_destination }}</em>
<em>{{ result.ride_comment }}</em>
{% endif %}
{% endfor %}
It is good to specify the related_name for ForeignKey as it makes life easier to access objects:
ride_id = models.ForeignKey(Ride, related_name='drivers')
Then you can do:
ride = Ride.objects.get(id='some_id')
drivers = ride.drivers.all()