I have Model Question and Answer.
What I want to accomplish is to be able to display it in the template in a way that shows like this. I would like to know a way to accomplish this. I'm trying my best to not let it loop the whole data in a model but rather one data at a time. I'm trying to make a qna data and make it display on a template. so having all the Questio data displayed before Answer data is not what I want. It has to be one by one for these two models. I'm getting kinda close...but I stil can't figure out how to accomplish this. Any help or advice would be greatly appreciated. Thank you in advance.
Q.title
Q.body
A.body
Q.title
Q.body
A.body
Q.title
Q.body
A.body
modesl.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class Question(models.Model):
title= models.CharField(max_length= 100)
body= models.TextField()
date_posted= models.DateTimeField(default=timezone.now)
author= models.ForeignKey(User, on_delete= models.CASCADE)
def __str__(self):
return self.title
class Answer(models.Model):
body= models.TextField()
question= models.ForeignKey(Question, on_delete= models.CASCADE)
date_posted= models.DateTimeField(default=timezone.now)
author= models.ForeignKey(User, on_delete= models.CASCADE)
def __str__(self):
return self.body
qna.html template
{% extends "info/base.html" %}
{% block content %}
{% for question in questions %}
<h1> Q</h1>
<h3> {{ question.title }} </h3>
{% for answer in answers %}
<h1> A </h1>
<h3> {{ answer.body }}</h3>
{% endfor %}
{% endfor %}
{% endblock content %}
views.py
from django.shortcuts import render
from .models import Question, Answer
def qna(request):
context= {
'questions': Question.objects.all(),
'answers': Answer.objects.all(),
}
return render(request, 'qna/qna.html', context)
As Answer model has relation of ForeignKey with question you can directly access question model fields in reverse.Replace your code in html like below and check if same works for you.
{% extends "info/base.html" %}
{% block content %}
{% for answer in answers %}
<h1> Question:</h1>
<h3> title: {{ answer.question.title }} </h3>
<h3> body: {{ answer.question.body }} </h3>
<h1> Answer: </h1><h3> {{ answer.body }} </h3>
{% endfor %}
{% endblock content %}
Add related_name to model Answer that has ForeignKey with Question:
question= models.ForeignKey(Question, on_delete= models.CASCADE, related_name='my_answes')
in HTML file replace the second loop with :
{% for answer in question.my_answes.all %}
<h1> A </h1>
<h3> {{ answer.body }}</h3>
<hr>
{% endfor %}
Related
I'm currently learning Django and I wanted to start off with a really simple blog app. I have a model for my post:
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(
'auth.User',
on_delete=models.CASCADE,
)
body = models.TextField()
Then I'm referencing it on my home page template:
{% extends 'base.html' %}
{% block content %}
{% for post in object_list %}
<div class="post-entry">
<h2>{{post.title}}</h2>
<p>{{post.body}}</p>
</div>
{% endfor %}
{% endblock content %}
I would like to make post.body to be only first 50 or so characters but post.body[:50] returns syntax error. How could I do that?
Try This:-
You can use
{{ post.body|truncatechars:50 }}
It will display only 50 characters of your Post Body
On a user's profile page right now it is displaying the number of people they are following and the usernames of the people they are following. When the user clicks on a username, I quite simply want it to take the user to that user's profile page but right now it is linking back to the same user's profile page, so essentially just reloading the page.
I am guessing it is because I am passing in user.username as a keyword argument because when I follow this same format but instead using user.id I don't run into this problem. I would like to use user.username so that the username can be displayed in the url.
rofilePage.html
{% block body %}
<h3>{{ user.username }}</h3>
<br>
<br>
<p>{{ profile.number_of_friends }}</p>
<p>{% for friend in profile.get_friends %}</p>
{{ friend }}<br>
{% endfor %}
{% endblock %}
views.py:
def profile_page(request, user_username):
profile = get_object_or_404(Profile, user__username=user_username)
return render(request, "network/profilePage.html", {
"profile": profile
})
urls.py:
path("profile/<str:user_username>", views.profile_page, name="profile"),
models.py:
class User(AbstractUser):
pass
class Profile(models.Model):
user = models.OneToOneField("User", on_delete=models.CASCADE, primary_key=True)
friends = models.ManyToManyField("User", related_name='following', blank=True, symmetrical=False)
<p>{% for friend in profile.get_friends %}</p>
{{ friend }}<br>
{% endfor %}
You are iterating over friends but not mentioning it, should be {{ friend }}<br>
{% for friend in profile.get_friends %}
is there a problem??
you are putting for in <p> tag?
try this:
{% for friend in profile.get_friends %}
<p>
{{ friend }}<br>
</p>
{% endfor %}
I'm new to Django, I repeat after the tutorial, but I just can not display comments even from the database in html.
urls.py
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
models.py
from django.db import models
class Post(models.Model):
photo = models.ImageField(upload_to='media/photos/',null=True, blank=True)
name_barber = models.CharField(max_length=30)
description = models.TextField(blank=True, null=True)
def __str__(self):
return self.description[:10]
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
name = models.CharField(max_length=255)
body = models.TextField()
date_add = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.post, self.name)
html file
} </style>
{% for post in posts %}
<img src="{{MEDIA_URL}}{{post.photo.url}}" width="800" />
<h3>{{ post.name_barber}}</h3>
<p>{{ post.description}}</p>
{% endfor %}
<h3> Comments.. </h3>
{% if not post.comments.all %}
no comments yet...Add one
{% else %}
{% for comment in post.comments.all %}
<strong>
{{ comment.name }}
{{ comment.date_add }}
</strong>
{{comment.body }}
{% endfor %}
{% endif %}
after adding a comment through the admin panel, the page displays: no comments yet..
What is the problem please tell me??
Remove the if/else condition and use the {% empty %} tag with your forloop.
{% for comment in post.comments.all %}
<strong>
{{ comment.name }}
{{ comment.date_add }}
</strong>
{{comment.body }}
{% empty %}
no comments yet...Add one
{% endfor %}
When I try to use foreignKey, html don't response
Models.py
class Home(models.Model):
book = models.ForeignKey(Book, verbose_name=(
"book"), on_delete=models.CASCADE, related_name="book")
Views.py
def main(request):
posts = Home.objects.all()
return render(request, 'home/home-page.html', {'posts': posts})
HTML
{% for post in posts %}
{% for book in post.book.all %}
{{ book }}
{% endfor %}
{% endfor %}
What going wrong?
all doesn't make any sense here, with a one to many relationship home only has one book, a book has many homes
so the inner for loop isn't needed, you can just use post.book
{% for post in posts %}
{{ post.book }}
{% endfor %}
I want to learn django and I should categorize my sql inputs according to my models.
For example I have some models like this:
class Author(models.Model):
authorName = models.CharField(max_length=30)
def __str__(self):
return self.authorName
class Book(models.Model):
author = models.ForeignKey(Authors, on_delete=models.CASCADE)
bookName = models.CharField(max_length=60)
downloadLink = models.FileField()
downloadCount = models.IntegerField(default=0)
def __str__(self):
return self.bookName
and I want to an output in my .html file like this;
Sherlock Holmes
A Study in Scarlet
The Sign of the Four
The Hound of the Baskervilles
Suzanne Collins
The Hunger Games
Catching Fire
Mockingjay
I tried this code in my html file but it doesn't work
<ul>
{% for author in all_authors %}
<h2>{{ author.authorName }}</h2>
{% for book in all_books %}
{% if book.author == author.authorName %}
<li>{{ book.bookName }}</li>
{% endif %}
{% endfor %}
{% endfor %}
</ul>
My output is;
Sherlock Holmes
Suzanne Collins
Here is my view.py file;
def books(request):
return render(request,'../templates/library/library-template.html', {
'all_authors': Author.objects.all(),
'all_books': Book.objects.all(),
})
How can I fix it? Or are there any different solution for fix this?
Thank you.. :)
Your if statement will never be true, you are comparing an object and a string
{% if book.author == author.authorName %}
So you could change this to
{% if book.author == author %}
But this is still wasteful, you can just use the reverse lookup so you won't need the if statement at all
<ul>
{% for author in all_authors %}
<h2>{{ author.authorName }}</h2>
{% for book in author.book_set.all %}
<li>{{ book.bookName }}</li>
{% endfor %}
{% endfor %}
</ul>