List One to Many Relationship - html

I'm sure this is a very basic question but I have a OneToMany Relationship and I wish to list all the associated children on a page. Here's what i have so far.
Model File
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=100)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse ('blog-post' , kwargs = {'pk': self.pk})
class Paragraph(models.Model):
content = models.TextField(default='')
post = models.ForeignKey(Post,default='', on_delete=models.CASCADE)
def __str__(self):
return self.content
class Subtitle(models.Model):
subtitle = models.CharField(max_length=100,default='')
post = models.ForeignKey(Post,default='', on_delete=models.CASCADE)
def __str__(self):
return self.subtitle
View
model = Post
template_name = 'blog/post.html'
context_object_name = 'post'
HTML FILE
{%block content%}
{% if post.author == user %}
Edit
Delete
{% endif %}
<div class = 'content'>
<h2>{{post.title}}</h2>
<!-- I want to show Subtitle here--><p></p>
<!-- I want to show Paragraph here--><p></p>
<h3>By: {{post.author}} on {{post.date_posted}}</h3>
</div>
{% endblock content %}

Isn't it's just {% for subtitle in post.subtitle_set.all %} {{ subtitle }} {% endfor %} and same for paragraph? – Charnel Feb 23 at 21:42

Related

I am not getting the value from the database

I am using MVT in django. I am using generic CBV (listview, detailview). here are my codes
Here is model.py
from django.db import models
class Singers(models.Model):
name= models.CharField(max_length=256)
age= models.IntegerField()
gender= models.CharField(max_length=10)
class Albums(models.Model):
name= models.CharField(max_length=256)
singer=models.ForeignKey(Singers, on_delete=models.CASCADE)
view.py
from django.views import generic
from core.models import Albums, Singers
#in generic view instead of functions, we use classes
class AlbumView(generic.ListView):
model = Albums
template_name = 'index.html'
paginate_by = 10
def get_queryset(self):
return Albums.objects.all()
class DetailView(generic.DetailView):
model = Albums
template_name = 'detailview.html'
Here are urls.py
from django.urls import path
from core.views import AlbumView, DetailView
urlpatterns = [
path('album/', AlbumView.as_view()),
path('album/detail/<pk>/', DetailView.as_view())
]
Here is index.html
{% block content %}
<h2>Albums</h2>
<ul>
{% for albums in object_list %}
<li>{{ albums.name }}</li>
{% endfor %}
</ul>
{% endblock %}
here is detailview.html
{% block content %}
<h1>name: {{Albums.name}}</h1>
<p><strong>Singer: {{Albums.Singer}}</strong></p>
{% endblock %}
The detail view is not working fine. It is not fetching the respective name of the album and singer details.
Suggest me what should i do?
Try this
{% block content %}
<h1>name: {{object.name}}</h1>
<p><strong>Singer: {{object.singer.name}}</strong></p>
{% endblock %}
class DetailView(generic.DetailView):
model = Albums
template_name = 'detailview.html'
This is not working you have to get first context like this
def get_context_data(self, **kwargs):
// Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
// Add in a QuerySet of all the books
context['Album_list'] = Albums.objects.all()
return context
And you can do as well
context_object_name = 'publisher'
queryset = Publisher.objects.all()

no such column: Homepage_goods.number_text

I have a problem of displayed a model text in index.html
This is code of views.py
class IndexView(generic.ListView):
template_name = 'Homepage/index.html'
model = Goods
context_object_name = 'goods'
def description(self):
return self.description_text
def price(self):
return self.price_text
def number(self):
return self.number_text
This is code of html(index.html)
{% for good in goods %}
<h3 class="numbers">{{good.number_text}}</h3>
{% endfor %}

How do i query all the fields in a django Many to Many

Trying to loop over a many to many relationship where I want all the fields.
My Models:
class Recipe(models.Model):
title = models.CharField(max_length=200)
slug = AutoSlugField(populate_from="title")
category = models.ForeignKey(RecipeTopic, on_delete=models.CASCADE)
image = models.ImageField()
description = models.TextField()
ingredients = models.ManyToManyField(Ingredient, through="IngredientList")
directions = models.TextField()
servings = models.IntegerField()
time = models.IntegerField()
cuisine = models.ForeignKey(Cuisine, on_delete=models.CASCADE)
def __str__(self):
return self.title
class IngredientList(models.Model):
ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
Recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
amount = models.FloatField(default=1)
unit = models.ForeignKey(Units, on_delete=models.CASCADE)
My Views:
from .models import Recipe
def home(request):
recipe = Recipe.objects.all()
context = {
"title": "Home Page",
"recipe": recipe
}
return render(request, "home.html", context)
and my template:
{%for r in recipe %}
<h2>{{r.title}}</h2>
<h4>Ingredients:</h4>
{%for i in r.ingredients.all %}
<p>---{{i.amount}}{{i.unit}} {{i.ingredient}}</p>
{%endfor%}
{%endfor%}
Want to showcase the ingredients, their amount, and the units that goes along with them. Except that I am only getting the "ingredient" title
You should query the reverse of the ForeignKey of your IngredientList model:
{% for r in recipe %}
<h2>{{r.title}}</h2>
<h4>Ingredients:</h4>
{% for i in r.ingredientlist_set.all %}
<p>---{{ i.amount }}{{ i.unit }} {{ i.ingredient }}</p>
{% endfor %}
{% endfor %}

How to display the users post to the user in the html form?

I have made a page where when the user logs in they can see their own posts but no posts are showing?
I have created an HTML and added the ginja tags representing the data in my post model but for some reason, it doesn't display my logged in users posts, only the empty HTML.
Here is my HTML file for users to view their own posts:
{% extends '../base.html' %}
{% block content %}
{% if post_list %}
<div class="container">
<div class="row">
<div class="col-md-8 card mb-4 mt-3 left top">
<div class="card-body">
<h1>{% block title %} {{ object.title }} {% endblock title %}</h1>
<p class=" text-muted">{{ post.author }} | {{ post.created_on }}</p>
<p class="card-text ">{{ object.content | safe }}</p>
Edit
Delete
</div>
</div>
</div>
</div>
{% endif %}
{% endblock content %}
Views File
class PostListbyAuthorView(generic.ListView):
model = Post
template_name = 'blog/post_list_by_author.html'
def get_queryset(self):
id = self.kwargs['pk']
target_author = get_object_or_404(PostAuthor, pk=id)
return Post.objects.filter(author=target_author)
def get_context_data(self, **kwargs):
context = super(PostListbyAuthorView, self).get_context_data(**kwargs)
context['post'] = get_object_or_404(PostAuthor, pk=self.kwargs['pk'])
return context
class IndexPage(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'blog/index.html'
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'blog/all_posts.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'blog/post_detail.html'
Models file
class PostAuthor(models.Model):
user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True)
bio = models.TextField(max_length=400, help_text="Enter your bio details here.")
class Meta:
ordering = ["user", "bio"]
def get_absolute_url(self):
return reverse('post-by-author', args=[str(self.id)])
def __str__(self):
return self.user.username
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(PostAuthor, on_delete=models.CASCADE, null=True, blank=True)
updated_on = models.DateTimeField(auto_now=True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-created_on']
def get_absolute_url(self):
return reverse('post-detail', args=[str(self.id)])
def __str__(self):
return self.title

django adds %EF%BB%BF at the end of my urls

I am working on a blog django app.
I have list of posts and a post detail pages.
when I click on a post title in the list should takes to the post detail page.
views.py
from django.shortcuts import render, get_list_or_404
from .models import Post
def list_of_post(request):
post = Post.objects.all()
template = 'blog/post/list_of_post.html'
context = {'post': post}
return render(request, template, context)
def post_detail(request, slug):
post = get_list_or_404(Post, slug=slug)
template = 'blog/post/post_detail.html'
context = {'post': post}
return render(request, template, context)
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.list_of_post, name='list_of_post'),
url(r'^(?P<slug>[-\w]+)/$', views.post_detail, name='post_detail')
]
models.py
from django.db import models
from django.utils import timezone
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published')
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250)
content = models.TextField()
seo_title = models.CharField(max_length=250)
seo_description = models.CharField(max_length=160)
author = models.ForeignKey(User, related_name='blog_posts')
published = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=9, choices=STATUS_CHOICES, default='draft')
def get_absolute_url(self):
return reverse('blog:post_detail', args=[self.slug])
def __str__(self):
return self.title
list_of_post.html
{% extends 'blog/base.html' %}
{% block title %}List of blog post{% endblock %}
{% block content %}
{% for posts in post %}
<h2>{{ posts.title }}</h2>
<p>Written by {{ posts.author }} on {{ posts.published }}</p>
<hr>
{{ posts.content|truncatewords:40|linebreaks }}
{% endfor %}
{% endblock %}
for some reason the url doesn't work. instead shows 404 that looks like this :
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/blog/practice-title/%EF%BB%BF
Using the URLconf defined in cms.urls, Django tried these URL patterns,in this order:
^admin/
^blog/ ^$ [name='list_of_post']
^blog/ ^(?P<slug>[-\w]+)/$ [name='post_detail']
The current URL, blog/practice-title/, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
and ideas?