I am trying to get the "About us" information from my database to my web application but its not displaying, what could be wrong...
here is the code from the database
class About(models.Model):
about_us = models.TextField()
achieve = models.TextField(blank=True)
image_abt = models.ImageField(upload_to="admin_pics", null=True)
class Meta:
verbose_name_plural = "About Us"
def __str__(self):
return self.about_us
and here is the Html code `
{% extends 'jtalks/base.html' %}
{% load static %}
{%block content%}
<section id="about-home">
<h2>About Us</h2>
</section>
<section id="about-container">
{% for about in abouts %}
<div class="about-img">
<img src="{{ about.image_abt.url }}" alt="">
</div>
<div class="about-text">
<h2>Welcome to TechEduca, Enhance your skills with best Online Courses</h2>
<p>{ about.about_us}</p>
<div class="about-fe">
<img src="images/fe1.png" alt="">
<div class="fe-text">
<h5>400+ Courses</h5>
<p>You can start and finish one of these popular courses in under our site</p>
</div>
</div>
<div class="about-fe">
<img src="images/fe2.png" alt="">
<div class="fe-text">
<h5>Lifetime Access</h5>
<p>You can start and finish one of these popular courses in under our site</p>
</div>
</div>
</div>
{% endfor %}
</section>
{% endblock %}
Nothing is displaying in the frontend of the website.
Thanks for sharing the view. You forgot to pass data to your template. To do that you have to create the queryset and pass that into a dictionary like below. Add the context variable to your render method so you can access the data in the template.
def about(request):
about = About.objects.all()
context = {
'abouts': about,
}
return render(request, 'jtalks/about.html', context)
also, in your html code i see { about.about_us}, but you have to use double curly brackets: {{ about.about_us }}
Related
I'm building an app in Django, using Bulma for styling. I have a Polishes model that has a favorites field, which references the User (users can save polishes to their list of favorites):
models.py:
class Polish(models.Model):
name = models.CharField(max_length=100)
image = models.CharField(max_length=400, default="https://www.dictionary.com/e/wp-content/uploads/2018/02/nail-polish-light-skin-tone.png")
brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name='polishes')
favorites = models.ManyToManyField(User, related_name='favorite', default=None, blank=True)
def __str__(self):
return self.name
The add_favorites function checks to see if the polish has been added to the user's favorites already, and if it has, it removes the polish from the list. If it hasn't, it adds it:
views.py:
# login_required
def add_favorite(request, id):
polish = get_object_or_404(Polish, id=id)
if polish.favorites.filter(id=request.user.id).exists():
polish.favorites.remove(request.user.pk)
else:
polish.favorites.add(request.user.pk)
return redirect('favorites_list')
When I render the list of polishes, I'm using Bulma cards, displaying one polish per card. In the footer of the card, I want it to say 'Save to Favorites' if the polish is not in the user's list of favoties and 'Remove from Favorites' if it is. I'm struggling to get this piece to work. It will currently show either Save to Favorites or Remove from Favorites on all of the cards.
Does anyone have any insight on how to render a different message only on those that are already on the favorites list?
polish_list.html:
...
<div class="gallery">
{% for polish in polishes %}
<a href="{% url 'polish_reviews' polish.pk %}">
<div class="card">
<div class="card-header">
<p class="card-header-title">{{polish.name}} by {{polish.brand}}</p>
</div>
<div class="card-image">
<figure class="image is-square">
<img src="{{polish.image}}" alt="{{polish.name}}" />
</figure>
</div>
<footer class="card-footer">
{% if polish.favorites %}
Remove from Favorites
{% elif user.is_authenticated %}
Save to Favorites
{% else %}
Save to Favorites
{%endif%}
</footer>
</div>
</a>
{% empty %}
<article class="message">
<div class="message-header">
<p>No Polishes Available</p>
</div>
</article>
{% endfor %}
</div>
...
I have tried using a conditional in my polish_list.html - {% if polish.favorites %} - but this will make the change on all of the cards rather than just on those that are saved to favorites.
I'm trying to show the correct articles in the category section using an if condition with a for loop inside, so far I'm displaying all the articles and not the only ones that supposed to be in the category.
home.html screeenshot
home.html
{% if articles.category == Sports %}
{% for article in articles %}
<div class="position-relative">
<img class="img-fluid w-100" src="{{article.cover.url}}" style="object-fit: cover;">
<div class="overlay position-relative bg-light">
<div class="mb-2" style="font-size: 13px;">
{{article.title}}
<span class="px-1">/</span>
<span>{{article.created_at}}</span>
</div>
<a class="h4 m-0" href="">{{article.description}}</a>
</div>
</div>
{% endfor %}
{% endif %}
views.py
def home (request):
cats = Category.objects.all()
articles = Article.objects.filter( is_published=True).order_by('-category')
return render (request,'pages/home.html',
context={
'cats': cats,
'articles': articles
})
Instead of hardcoding it like that, you could let the users search for categories with something like this:
articles = Article.objects.filter(category__icontains=q).values('title')
where q would be the user input in the form.
I'm trying to develop a search functionality but only getting a empty query set every single time .
class SearchView(TemplateView):
template_name = "search.html"
def get_context(self, **kwargs):
context = super().get_context(**kwargs)
kw = self.request.GET.get("search")
results = Thread.objects.filter(Q(heading__icontains=kw) | Q(thread_content__icontains=kw))
print(results)
context["results"] = results
return context
Template
{% extends 'base.html' %}
{% block title %}Search{% endblock %}
{% block content %}
<div class = "container">
<div class = "row">
<div class = "col-md-12">
<h3>Search results for <span class="text-info">"{{ request.GET.search }}"</span></h3>
<h3>{{results}}</h3>
<hr>
{% for item in results %}
<div class="col-md-4">
<img src = "{{item.image.url}}" class="img-fluid" alt = "">
</div>
<div class="col-md-8">
<h4>{{item.heading}}</h4>
<p>{{item.thread_content}}</p>
</div>
{%endfor%}
</div>
</div>
</div>
{% endblock %}
request.GET.search is returning correctly , but the rest is not getting displayed
This was a real strange issue. The Browser cache took a long time to refresh with my updated code. Once I cleared the Browser Cache and Settings, it started working again.
I am asking this question again because I did not receive a satisfactory answer in my previous attempt. It may be difficult for me to fully convey the issue I am trying to resolve, but I will do my best to provide a clear and concise explanation.
.
I am trying to run a query that retrieves a list of followers, as well as the list of followers and followings for each follower. I have included an image that illustrates this structure. I am currently using the following code to attempt this, but it is not producing the expected results. Can you help me understand what I am doing wrong and how I can correctly run this query?
views.py
def get_context_data(self, *args, **kwargs):
context = super(FollowerView,self).get_context_data(*args, **kwargs)
user = context['user']
user_com = User.objects.get(username=user)
myfollowers = user_com.is_following.all()
followers_Array =[]
followerings_Array =[]
for target_list in myfollowers:
user_obj = User.objects.get(username=target_list)
followers_obj = user_obj.is_following.all()
print(followers_obj,'name o ki line')
followerings_Array.append(followerings_Array)
print(followers_obj,user_obj)
followerings_obj = user_obj.userprofile.follower.all()
followerings_Array.append(followerings_obj)
print(followerings_obj,user_obj)
print(followerings_Array,'arry one one one ')
context['myfollowers_data']= followers_Array
context['myfollowerings_data']= followerings_Array
return context
I am currently using two arrays in my code, but I would prefer to avoid doing so if possible. My current implementation is not producing the desired output when I return the arrays in the context. Can you suggest an alternative approach that allows me to display the data in the manner illustrated in the image, and can you review the followers template to see if I am making any mistakes there?
{% for follower in user.is_following.all %}
<div class="followers-body">
<img class="img-responsive img-circle" src="{{follower.avatar.url}}" alt="">
<div class="name-box">
<h4>{{follower}}</h4>
<span>#{{follower}}</span>
<div class="followers-base">
<ul class="list-group">
<li class="list-group-item full-width">
<div class="pull-left" style="margin-right: 20px;">
{% if myfollowers_data %}
{% for user in myfollowers_data %}
<img src="{{user.userprofile.avatar.url}}" alt="" class="img-circle max-w-40 ">
{% endfor %}
{% endif %}
<span> {{myfollowers_data.count}} Followers </span>
</div><!--/ pull-left -->
</li>
<li class="list-group-item full-width">
<div class="pull-left">
{% for usr in myfollowerings_data %}
<img src="{{usr.userprofile.avatar.url}}" alt="" class="img-circle max-w-40 ">
{% endfor %}
<span> {{myfollowerings_data|length}} Following </span>
</div><!--/ pull-right -->
</li><!--/ list-group-item -->
</ul>
</div><!--/ followers-base -->
</div><!--/ name-box -->
<span> Follow</span>
</div><!--/ followers-body -->
{% endfor %}
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
follower = models.ManyToManyField(User, related_name ='is_following',blank=True,)
close_friends = models.ManyToManyField(User,related_name='my_close_friends', blank=True)
rank = models.ManyToManyField(Rank, related_name='rank', default='Newbie', blank=True)
avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True)
create_date = models.DateField(auto_now_add=True,null=True)
#property
def email_address(self):
return self.user.email
objects = ProfileManager()
def __str__(self):
return f'{self.user.username}'
def get_absolute_url(self):
return reverse("profiles:final_detail", kwargs={"username": self.user.username})
If more code in require than tell me in a comment session. I will update my question with that information.
Okay, this should all be achievable from the template:
template.html:
<!-- users followers -->
{% for follower1 in user.is_following.all %}
<img src="{{ follower1.avatar.url }}"/>
<!-- followers followers -->
{% for follower2 in follower1.is_following.all %}
<img src="{{ follower2.avatar.url }}"/>
...
{% endfor %}
{% endfor %}
am new to Django and am trying to create a blog site where users can sign up and post articles, but my problem is how can I display a user's post on the user's profile page so that when other users reading the post clicks on the author's name it takes them to the post.author's profile page with the post.author's recent post listed and not the request.user's post. here is my code.
here is accounts/views.py
views.py
#login_required()
def user_profile_view(request, username):
post = User.objects.filter(courses__author=username)
context = {'courses': courses}
return render(request, 'accounts/user_profile_view.html', context)
and here is post/models.py
models.py
class Posts(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
cover = ProcessedImageField(upload_to='post_featured_image',
processors=[ResizeToFill(600, 300)],
format='png',
options={'quality': 80},
blank=True)
slug = models.SlugField()
title = models.CharField(max_length=200)
body = models.TextField()
summary = models.TextField(max_length=200)
here is the template
post_list.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="col-lg-6">
{% for course in courses_list %}
<div class="central-meta item">
<div class="user-post">
<div class="friend-info">
{% if post.author.profile.avatar %}
<figure>
<img src="{{ post.author.profile.avatar.url }}" alt="">
</figure>
{% else %}
<img src="{% static 'default.ico' %}" alt="">
{% endif %}
<div class="friend-name">
<ins>{{ course.author.get_full_name|title }}</ins>
<span>published: {{ post.published }}</span>
</div>
<div class="post-meta">
{% if course.cover %}
<img src="{{ post.cover.url }}" alt="">
{% endif %}
<div class="friend-name">
<ins>{{ course.title|title }}</ins>
</div>
<div class="description">
<p><span>{{ post.summary|capfirst }}</span></p>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
here is my accounts/urls.py
urls.py
app_name = 'accounts'
urlpatterns = [
path('accounts/profile/<str:username>/', user_profile_view, name='user_profile'),
]
you should be able do that, easy and via lots of ways.
make a post model like this:
class Post(models.Model):
author = foreign_key(User, related_name="posts", on_delete=models.CASCADE)
title = char_field()
content ........
so with that related name you will be able to reverse from user to its posts too!.
in your template do this:
{{ post.author }}
this link will redirect user to the posts author dashboard if you arrange the urls pattern correctly.
then for sorting authors posts, you have to pass the dashboard_owner to the template and use this name instead of user which normally will refer to the request.user -> user who are visiting the page
{% for post in dash_owner.posts.all %}
<li> <a href="{{ post.get_abslute_url }}" target="_blink">
{{ post.title }} </a> </li>
{% endfor %}
in views.py
def dashboard(request, owner_id=None)
if owner_id:
dash_owner = get_or_404(User, id=owner_id)
elif request.user.is_authenticated:
dash_owner = User.objectd.get(id=request.user.id)
return render(request, 'dashboard.html', {'dash_owner': dash_owner})
in urls.py -> urlpatterns:
path('dashboard/<int:owner_id>/', views.dashboard, name="dashboard")
this is the idea behind that, but for get the better result, you may need to clearly define the get_absolute_url of User model, to give you the url which machts to
'dashboard/<int:id/'
or another way is instead of that, do this:
{{ post.author }}