how to iterate on two subclass models with same for loop? - django

I want to create a photo sharing website, but i don't know how to iterate over
this code:
all_post = Images.objects.all().order_by('-created').select_subclasses()
my models.py
class Images(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created', on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
objects = InheritanceManager()
class Postimg(Images):
user_img= models.ImageField(upload_to='images/%Y/%m/%d', null=True, blank=True)
class Postsms(Images):
user_message = models.CharField(max_length=500,blank=True)
views.py
#login_required
def home(request):
all_post = Images.objects.all().order_by('-created').select_subclasses()
return render(request, 'copybook/home.html',{ 'all_post':all_post})
home.html
{% for foo in all_post %}
<hr>
<br> SMS by: <p>{{ foo.user}} __ {{ foo.created }}</p> <br>
<h2>{{ foo.user_message }}</h2>
<hr>
<br> IMAGE by: <p>{{ foo.user}} __ {{ foo.created }}</p> <br>
<img src="{{ foo.user_img.url }}"width="250">
{% endfor %}
how do i iterate it in home.html

Related

Django - Giving a view access to multiple models

I followed a tutorial on Youtube that makes a website to create posts. Currently, I am working on displaying other people's profiles and their posts on their profile pages. I did it by accessing the author of the first post, but it only works if the user posted something. Is there another way to do it?
The view:
class UserProfileView(ListView):
model = Post
template_name = 'blog/user_profile.html' # defaults to <app>/<model>_<viewtype>.html--> blog/post_list.html
context_object_name = 'posts' #defaults to objectlist
paginate_by = 5
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get('username'))
return Post.objects.filter(author=user).order_by('-date_posted')
user_profile.html:
{% extends 'blog/base.html' %}
{% block title %}{{ view.kwargs.username }}'s Profile{% endblock title %}
{% block content %}
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ posts.first.author.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ view.kwargs.username }}</h2>
<p class="text-secondary">{{ posts.first.author.email }}</p>
<p class="article-content">{{ posts.first.author.profile.bio }}</p>
</div>
</div>
{% if posts.first.author == user %}
<a class="btn btn-outline-secondary ml-2" href="{% url 'change_profile' %}">Edit Profile</a>
{% endif %}
</div>
<br>
{% if posts.first.author == user %}
<h3 class="ml-2 article-title">Blogs You Posted</h3>
{% else %}
<h3 class="ml-2 article-title">Blogs By {{ view.kwargs.username }}</h3>
{% endif %}
And the Post and Profile module:
class Post(models.Model):
title = models.CharField(max_length=50)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self) -> str:
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk':self.pk})
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
bio = models.CharField(max_length=225, blank=True, default='')
def __str__(self) -> str:
return f"{self.user.username}'s Profile"
def save(self, *args, **kwargs):
super(Profile, self).save(*args, **kwargs)
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
img.thumbnail((300,300))
img.save(self.image.path)
First off, you probably don't need .first in your template, because you are using the first item from the QuerySet. If you are accessing a User profile, you can use the DetailView. In addition, you can try from a different page and provide filtered posts in context. Something like this, for example.
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['posts'] = Post.objects.filter(author=user) # from kwargs
return context
#template
<ul>
{% for post in posts %}
<li>{{ post.title }}</li>
<li>{{ post.content }}</li>
<li>{{ post.date_posted }}</li>
{% endfor %}
</ul>
PS Regards to Corey.

Django - how to get all the users in team when using a costumised user model

I am new to django and have a question: I created a CustomUser model within a users app.
I tried
from users.models import CustomUser, Team
team1= Team.objects.first()
users_team1= team1.user.objects.all()
and it doesnt get me the list of users in this Team
class CustomUser(AbstractUser):
bio= models.CharField(max_length=300, null= True, blank=True)
class Team (models.Model):
title = models.CharField(max_length=200)
user= models.ManyToManyField(get_user_model())
date_created= models.DateTimeField(auto_now_add=True, blank=True, null=True)
date_updated= models.DateTimeField(auto_now=True,blank=True, null=True )
def __str__(self):
return self.title
def get_absolute_url(self): # new
return reverse('team_detail', args=[str(self.pk)])
I want created a HTML page
{% extends '_base.html' %}
{% block title %}{{ object.title }}{% endblock title %}
{% block content %}
<div class="team-detail">
<h2>{{ team.title }}</h2>
<p>Team tile : {{ team.title }}</p>
<p>user: {{ team.user }}</p>
</div>
{% endblock content %}
how can i show all the users in a specific Team?
Thanks in advance.
You should do:
from users.models import CustomUser, Team
team1= Team.objects.first()
# lets pass team1 to your template
return render(request, 'template/name.html', {'team': team1})
Your template should be sthg like:
{% extends '_base.html' %}
{% block title %}{{ object.title }}{% endblock title %}
{% block content %}
<div class="team-detail">
<h2>{{ team.title }}</h2>
<p>Team tile : {{ team.title }}</p>
{% for user in team.user.all %}
<p>user: {{ user }}</p>
{% endfor %}
</div>
{% endblock content %}

In django, getting the following usernames in user profile

i'm building a following model. I have created a following model as shown below and it is working fine in the admin. I did not create a view for the following because i'm in primary stage of building i'm testing in templates to bring that usernames in userspostlist, but it's not working.
my models.py for following:
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='owner', on_delete=models.CASCADE)
following = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='followed_by')
def __str__(self):
return str(self.following.all().count())
class post(models.Model):
parent = models.ForeignKey("self", on_delete=models.CASCADE, blank=True, null=True)
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='post_pics', null=True, blank=True)
video = models.FileField(upload_to='post_videos', null=True, blank=True)
content = models.TextField()
likes = models.ManyToManyField(User, related_name='likes', blank=True)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
objects = postManager()
def __str__(self):
return self.title
my views.py for userpostlist:
class UserPostListView(ListView):
model = post
template_name = 'blog/user_post.html' #<app>/<model>_<viewtype>.html
context_object_name = 'posts'
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get('username'))
return post.objects.filter(author=user).order_by('-date_posted')
and my userpostlist.html:
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<h1 class="mb-3">posts by {{view.kwargs.username}}</h1>
{% for user in username.owner.following.all %}
{{ user.username }}
{% endfor %}
{% for post in posts %}
<article class="content-section">
<div class="article-metadata">
<div class="img">
<img class="rounded-circle article-img" data-toggle="modal" data-target="#mymodal" src="{{ post.author.profile.image.url }}">
</div>
<div class="profile-info">
<a class="h2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a>
<div class="text-muted">{{ post.date_posted }}</div>
</div>
</div>
{% endfor %}
{% endblock content %}
Is there any problem with the userpostlist view in views.py? do i need to add some code there?
You have some options here, where one is to pass users into context:
class UserPostListView(ListView):
...
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['author'] = get_object_or_404(User, username=self.kwargs.get('username')
return context
And then instead of this:
{% for user in username.owner.following.all %}
{{ user.username }}
{% endfor %}
Use this:
{{ author.username }}

How to use Outer for loop value in inner for loop in Django template

I'm doing Django Project. Here I am trying to use Outer for loop data in inner for loop in Django Template. Help me in that i did mistake in inner for loop i don't know how to solve this.
views.py
def test_view(request):
if 'username' in request.session:
if request.method == 'GET':
offers_objs = Offers.objects.all().values()
data = Signup.objects.all().values()
return render(request, 'index.html',{'offers_objs':offers_objs, 'data': data})
index.html
{% for i in offers_objs %}
<div class="divi" style="height: 410px">
<img src="{{ i.image.url }}" alt="Images" width="300px" height="auto"/>
<p>Offer Des: {{ i.description }}</p>
<p>Address: {{ i.address }}</p>
<p>Offer id: {{ i.offer_id }}</p>
</div>
{% for {{ i.username }} in data %}
<p>{{ name }}</p>
{% endfor %}
{% endfor %}
models.py
class Signup(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
email = models.EmailField(max_length=50, unique= True)
phone_number = models.CharField(max_length=12, unique= True)
username = models.CharField(max_length=50, unique= True)
password = models.CharField(max_length=50, blank=True, null=True)
address = models. CharField(max_length=50, blank=True, null=True)
class Offers(models.Model):
offer_id = models.CharField(max_length=100, blank=True, null=True)
description = models.CharField(max_length=100, blank=True, null=True)
username = models.CharField(max_length=100, blank=True, null=True)
Removing the {{ }} in {% for {{ i.username }} in data %} should fix it.
{% for i in offers_objs %}
<div class="divi" style="height: 410px">
<img src="{{ i.image.url }}" alt="Images" width="300px" height="auto"/>
<p>Offer Des: {{ i.description }}</p>
<p>Address: {{ i.address }}</p>
<p>Offer id: {{ i.offer_id }}</p>
</div>
{% for i.username in data %}
<p>{{ name }}</p>
{% endfor %}
{% endfor %}

Django unrecognized token: "#" while query

I simply want to implement a search view into my Django app. But when i try to search something on my App i get the following error:
'unrecognized token: "#"'
In the end i want that my Query is a combination of category and searchword. So that the user can filter specific categories (Just like Amazon.com searchfield) e.g.: http://127.0.0.1:8000/search/?category=1&q=hallo
base.html
...
<div class="globalsearch">
<form id="searchform" action="{% url 'search' %}" method="get" accept-charset="utf-8">
<label for="{{ categorysearch_form.category.id_for_label }}">In category: </label> {{ categorysearch_form.category }}
<input class="searchfield" id="searchbox" name="q" type="text" placeholder="Search for ...">
<button class="searchbutton" type="submit">
<i class="fa fa-search"></i>
</button>
</form>
</div>
</div>
...
categorysearch_form is a dropdown selector that gets his ID from the Database.
views.py
...
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
from django.views.generic import ListView
class globalsearch(ListView):
"""
Display a Post List page filtered by the search query.
"""
model = Post
paginate_by = 10
def get_queryset(self):
qs = Post.objects.all()
keywords = self.request.GET.get('q')
if keywords:
query = SearchQuery(keywords)
title_vector = SearchVector('title', weight='A')
content_vector = SearchVector('content', weight='B')
tag_vector = SearchVector('tag', weight='C')
vectors = title_vector + content_vector + tag_vector
qs = qs.annotate(search=vectors).filter(search=query)
qs = qs.annotate(rank=SearchRank(vectors, query)).order_by('-rank')
return qs
...
urls.py
...
url(r'^search/$', views.globalsearch.as_view(), name='search'),
...
Search.html results are getting displayd here:
{% extends 'quickblog/base.html' %}
{% block content %}
{% for post in object_list %}
<div class="post">
<h1><u>{{ post.title }}</u></h1>
<p>{{ post.content|linebreaksbr }}</p>
<div class="date">
<a>Published by: {{ post.author }}</a><br>
<a>Published at: {{ post.published_date }}</a><br>
<a>Category: {{ post.category }}</a><br>
<a>Tag(s): {{ post.tag }}</a>
</div>
</div>
{% endfor %}
Post Model
...
#Post Model
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=75)
content = models.TextField(max_length=10000)
tag = models.CharField(max_length=50, blank=True)
category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
postattachment = fields.FileField(upload_to='postattachment/%Y/%m/%d/', blank=True ,null=True)
postcover = fields.ImageField(upload_to='postcover/%Y/%m/%d/', null=True, dependencies=[
FileDependency(processor=ImageProcessor(
format='JPEG', scale={'max_width': 200, 'max_height': 200}))
])
created_date = models.DateField(auto_now_add=True)
published_date = models.DateField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
class Meta:
ordering = ["-title"]
def __str__(self):
return self.title
...
i guess im simply missing something
at that point...
I already read that this issue comes from local SQL database aka. SQLite, could that be true?
Smb. has a solution?
Thanks
After a bit of tinkering with a friend i found a solution, the Django Documentation according to vector searching is really not that good...
views.py
class globalsearch(ListView):
"""
Display a Post List page filtered by the search query.
"""
model = Post
paginate_by = 10
template_name = 'quickblog/search.html'
def get_queryset(self):
keywords = self.request.GET.get('q')
if keywords:
query = SearchQuery(keywords)
title_vector = SearchVector('title', weight='A')
content_vector = SearchVector('content', weight='B')
tag_vector = SearchVector('tag', weight='C')
vectors = title_vector + content_vector + tag_vector
qs = Post.objects.annotate(rank=SearchRank(vectors, query)).filter(rank__gte=0.1).order_by('-rank')
return qs
models.py
#Post Model
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=75)
content = models.TextField(max_length=10000)
tag = models.CharField(max_length=50, blank=True)
category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
postattachment = fields.FileField(upload_to='postattachment/%Y/%m/%d/', blank=True ,null=True)
postcover = fields.ImageField(upload_to='postcover/%Y/%m/%d/', null=True, dependencies=[
FileDependency(processor=ImageProcessor(
format='JPEG', scale={'max_width': 200, 'max_height': 200}))
])
created_date = models.DateField(auto_now_add=True)
published_date = models.DateField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
class Meta:
ordering = ["-title"]
def __str__(self):
return self.title
search.html
{% extends 'quickblog/base.html' %}
{% block content %}
{% for post in object_list %}
<div class="post">
<h1><u>{{ post.title }}</u></h1>
<p>{{ post.content|linebreaksbr }}</p>
<div class="date">
<a>Published by: {{ post.author }}</a><br>
<a>Published at: {{ post.published_date }}</a><br>
<a>Category: {{ post.category }}</a><br>
<a>Tag(s): {{ post.tag }}</a>
</div>
</div>
{% endfor %}
{% if is_paginated %}
<ul class="pagination">
{% if page_obj.has_previous %}
<li>«</li>
{% else %}
<li class="disabled"><span>«</span></li>
{% endif %}
{% for i in paginator.page_range %}
{% if page_obj.number == i %}
<li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
{% else %}
<li>{{ i }}</li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li>»</li>
{% else %}
<li class="disabled"><span>»</span></li>
{% endif %}
</ul>
{% endif %}
{% endblock %}
urls.py
url(r'^search/$', views.globalsearch.as_view(), name='search'),
Hope that i was able to help the next one with that Post :D