Django displaying all users - python

I want to display all the users, in my template but I cannot. I think there is a mistake in my codes but I cannot find it. Here is codes.
views.py
class UsersView(TemplateView):
template_name = 'users.html'
def get_context_data(self, **kwargs):
context = super(UsersView, self).get_context_data(**kwargs)
context['object_list'] = UserList.objects.all()
return context
models.py
class UserList(AbstractBaseUser):
first_name = models.CharField(max_length=200, blank=True, help_text="The first name of the user.")
last_name = models.CharField(max_length=200, blank=True, help_text="The last name of the user.")
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
help_text="The email and username of the user. Required."
)
users.html
{% extends 'blog/base.html' %}
{% block content %}
<h1>Users:</h1>
<ul>
{% for users in object_list %}
<li class="user">{{ user }}</li>
{% endfor %}
</ul>
{% endblock %}
And this is the page that I get:
Where is my mistake? Thank you.

Your code includes the following:
{% for users in object_list %}
<li class="user">{{ user }}</li>
{% endfor %}
The trouble with this is that the user template variable is not defined. Change users to user in the loop header and you should be OK.

You can use django.contrib.auth.models.User on your view with request.user.get_username() with this you use a standard user with Django. If go go admin URL you see user default.
For call in template :
{{ user.get_username }}

Related

How do I show navbar items based on a model field in Django?

I have a Blog model that looks like this:
class Blog(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blogs')
parent = models.CharField(max_length=50, choices=PARENT_TUTORIALS)
def get_absolute_url(self):
return reverse("blog_list", args=[str(self.parent), str(self.slug)])
I can succesfully display all the blogs on a table of contents via my table.html template:
{% for blog in blog_list %}
<li>{{blog.title}}</li>
{% endfor %}
However, I want to show only those blogs that have the same Blog.parent value as the current blog page. For example, the page example.com/biology/page1, has biology as a parent. When the user is on that page, the table of contents should show only the pages that have biology as a parent.
Why not just add an if statement like so?
template.html
{% for blog in blog_list %}
{% if blog.parent == current_blog.parent %}
<li>{{blog.title}}</li>
{% endif %}
{% endfor %}
Another option is to filter with js, something like (untested):
template.html
{% for blog in blog_list %}
<li class="blog-list-item {{blog.parent}}">
{{blog.title}}
</li>
{% endfor %}
script.js
$('.blog-list-item').filter(':not(.biology)').hide();

How to acces the the django ManyToMany Field in django Template

I have set of attributes in my Models from which one of the attribute is of Type ManyToMany Field. I am able to access all the Attributes in Template instead one which is ManyToMany Field.
I have tried following in my template
{% for post in all_posts %}
{{ post.likes }}
{% endfor %}
models.py
class Posts(models.Model):
title = models.CharField(max_length=250, blank=False)
content = models.CharField(max_length=15000,
help_text="Write Your thought here...")
creation_time = models.DateTimeField(auto_now_add=True, editable=False)
likes = models.ManyToManyField(User, blank=True, related_name='likes')
views.py
def home(request):
template = loader.get_template('home.html')
all_posts = Posts.objects.all()
context = {
'all_posts': all_posts,
}
return HttpResponse(template.render(context, request))
When i Use {{ post.likes }} what renders on page is auth.User.None
You will have to traverse over all the likes for the selected post
Try something like this:
{% for post in all_posts %}
{% for like in post.likes.all %}
{{ like }}
{% endfor %}
{% endfor %}

Django filter queryset in reverse relation

Code I'm working with:
class Message(models.Model):
from_who = models.ForeignKey(User, related_name='sent')
to = models.ForeignKey(User, related_name='recieved')
text = models.CharField(max_length=1000)
timestamp = models.DateTimeField(auto_now_add=True)
new = models.BooleanField(default=True)
Can I display in template User.recieved messages only with new = True when I'm using request.user not context? If yes, how?
If I understand the question - you want to show all new message to the logged in user without adding any additional context to the view? Try this (and note that I changed the spelling of "received":
{% for message in request.user.received.all %}
{% if message.new %}
{{ message }}<br />
{% endif %}
{% endfor %}
For someone who is looking an answer:
#models.py
class Message(models.Model):
from_who = models.ForeignKey(User, related_name='sent')
to = models.ForeignKey(User, related_name='recieved')
text = models.CharField(max_length=1000)
timestamp = models.DateTimeField(auto_now_add=True)
new = models.BooleanField(default=True)
new_messages = NewMessageManager()
#managers.py
class NewMessageManager(models.Manager):
def new_messages(self):
return super(NewMessageManager, self).get_queryset().filter(new=True)
#template.html
{% if request.user.recieved.new_messages %}
<span class="badge badge-danger">{{ request.user.recieved.new_messages.count }}</span>
{% endif %}

Django Template - show many-to-many relationship

I'm learning Django after having built some basic apps in Flask. One thing I want to do is show users a list of all posts and whether or not they follow that given post. However, Jinja or Django is throwing some error that I don't quite know how to debug.
Models.py
class User(models.Model):
id = models.AutoField(primary_key=True)
username = models.CharField(unique=True, max_length=120,blank=False)
password = models.CharField(max_length=120, blank=True, null=False)
class Record(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=120, unique=True, blank=True)
followers = models.ManyToManyField(User, through='Follow')
class Follow(models.Model):
id = models.AutoField(primary_key=True)
record = models.ForeignKey(Record)
user = models.ForeignKey(User)
date_followed = models.DateField(null=True, blank=True)
records.html
{% for i in records %}
{% if i.follow.filter(id='1').first() %}
DO SOMETHING
{% endif %}
{% endfor %}
error
TemplateSyntaxError at /records/
Could not parse the remainder: '(id='1').first()' from 'i.follow.filter(id='1').first()'
To test this out when I run the python manage.py shell and execute the following I have no issues:
>>> x = Record.objects.first()
>>> x.followers.filter(id='1').first()
<User: User object>
I had initially prototyped this app using Flask and had the following jinja template and never had an issue:
{% for i in accounts %}
{% if i.follow.filter_by(user_id='1').first() %}
DO SOMETHING
{% endif %}
{% endfor %}
You cannot do that logic in template. You can create a method in Record model that does it for you and you can call it in template
class Record(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=120, unique=True, blank=True)
followers = models.ManyToManyField(User, through='Follow')
def first_follower(self):
if self.follow_set.filter(user_id=1).exists():
return True
return False
and in template:
{% for i in records %}
{% if i.first_follower %}
DO SOMETHING
{% endif %}
{% endfor %}
This is by design https://code.djangoproject.com/ticket/1199
The idea is that a django template should focus on design, for designers, and let the more complex code run in Python, not when the template renders.
So if this is a single instance when you use this check, add it to the view:
def get_context_data(self,*arg,**kwargs):
context = super(MyRecordView,self).get_context_data(*args,**kwargs)
context[has_follow] = self.object.follow.filter_by(user_id='1').exists()
return context
In the template:
{% if has_follow %}
...
{% endif %}
However, if you use this check a lot, you can add it to your model:
def has_follow(self):
return self.follow.filter_by(user_id='1').exists()
And then you can access it in a template, w/o any changes to the view context, since it's a model attribute:
{% if i.has_follow %}
...
{% endif %}

Extra "row-level" data in ListView django

I'm writing my first django app and can't seem to pass "row-level" data to the template through ListView. Specifically I'm trying to show all Polls and their corresponding Vote information using a PollListView.
Currently I am only able to pass all votes to the template, but would like to pass only the votes that belong to the specific poll.
models.py
class Poll(models.Model):
user = models.ForeignKey(User, unique=False, blank=False, db_index=True)
title = models.CharField(max_length=80)
class Vote(models.Model):
poll = models.ForeignKey(Poll, unique=False, blank=False, db_index=True)
user = models.ForeignKey(User, unique=False, blank=True, null=True, db_index=True)
vote = models.CharField(max_length=30, blank=False, default='unset', choices=choices)
views.py
class PollListView(ListView):
model = Poll
template_name = 'homepage.html'
context_object_name="poll_list"
def get_context_data(self, **kwargs):
context = super(PollListView, self).get_context_data(**kwargs)
context['vote_list'] = Vote.objects.all()
return context
urls.py
urlpatterns = patterns('',
...
url(r'^$', PollListView.as_view(), name="poll-list"),
}
homepage.html
{% for poll in poll_list %}
{{ poll.title }}
{% for vote in vote_list %}
{{ vote.id }} {{ vote.vote }}
{% endfor %}
{% endfor %}
Seems like an easy task, but I can't seem to figure out how to do this using class-based views. Should I be using mixins or extra_context? Overwrite queryset? Or should I just used function-based views to solve this.
Any help would be greatly appreciated.
I'm not sure if it's gonna work, but you can try the following:
models.py (Vote class)
poll = models.ForeignKey(Poll, related_name="votes", unique=False, blank=False, db_index=True)
views.py
class PollListView(ListView):
queryset = Poll.objects.all().prefetch_related('votes')
with that you can access related votes:
template
{% for poll in poll_list %}
{{ poll.title }}
{% for vote in poll.votes.all %}
{{ vote.id }} {{ vote.vote }}
{% endfor %}
{% endfor %}

Categories