I'm creating a page that has one video , as many comments , replies for each comment
I could retrieve video and comments but replies for each comment haven't been retrieved eventually.
I made some for loops in views file but didn't know also how to retrieve it in the templates file.
I'm stuck between views and templates till now
I'm using django 1.10.4
models.py
class Video(models.Model):
title = models.CharField(max_length=120)
embed_code = models.CharField(max_length=500)
slug = models.SlugField(null=True, blank=True)
category = models.ForeignKey("Category", null=True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
active = models.BooleanField(default=True)
featured = models.BooleanField(default=False)
free_preview = models.BooleanField(default=False)
share_message = models.CharField(max_length=150, default=default_share_message)
objects = models.Manager()
# activemodel = ActiveModel()
featuresandactive = Features()
class Meta:
unique_together = ('slug', 'category')
def __str__(self):
return self.title
def get_absolute_url(self):
try:
return reverse('video_detail', kwargs={'vid_slug':self.slug, 'cat_slug':self.category.slug})
except:
return "/"
class Comment(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(MyUser)
path = models.CharField(max_length=350)
video = models.ForeignKey(Video, null=True, blank=True)
text = models.TextField()
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
Timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
active = models.BooleanField(default=True)
objects = CommentManager()
def __str__(self):
return self.text
class Reply(models.Model):
user = models.ForeignKey(MyUser)
comment = models.ForeignKey(Comment,null=True, blank=True)
text = models.TextField()
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
Timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
active = models.BooleanField(default=True)
objects = ReplyManager()
def __str__(self):
return self.text
views.py
def video_detail(request, cat_slug, vid_slug):
cat = Category.objects.get(slug=cat_slug)
comments = Comment.objects.filter(video=obj)
replys = Reply.objects.filter(comment=comments)
context = {
"cat": cat,
"obj":obj,
"comments":comments,
"replys":replys,
}
return render(request, 'video_detail.html', context)
this is another view.py
I tried this also but didn't work
def video_detail(request, cat_slug, vid_slug):
cat = Category.objects.get(slug=cat_slug)
obj = Video.objects.get(slug=vid_slug)
comments = obj.comment_set.all()
Replies = Reply.objects.filter(comment_id=comments.id))
context = {
"cat": cat,
"obj":obj,
"comments":comments,
"replies":replies
}
return render(request, 'video_detail.html', context)
IMO, you can represent the comments in your template. your template may look like this.
# your_template.html
{% for comment in obj.comment_set.all %}
{{comment.user}}: {{comment.text}}
{% for reply in comment.reply_set.all %}
{{reply.user}}: {{reply.text}}
{% endfor %}
{% endfor %}
then your view function only needs cat and obj, not comments or replies. also check out select_related.
Related
I have two models:
class Post(models.Model):
title= models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
postimage = models.ImageField(null= True, blank= True, upload_to="images/")
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title + " | "+ str(self.author)
def get_absolute_url(self):
return reverse('article_deatil', args=(str(self.id)))
class AboutMe(models.Model):
title1= models.CharField(max_length=255, default="About Me")
body = models.TextField()
skill1= models.CharField(max_length=255)
skill1body = models.TextField()
skill2= models.CharField(max_length=255)
skill2body = models.TextField()
skill3= models.CharField(max_length=255)
skill3body = models.TextField()
edu1=models.CharField(max_length=255)
edu1body = models.TextField()
edu2=models.CharField(max_length=255)
edu2body = models.TextField()
edu3=models.CharField(max_length=255)
edu3body = models.TextField()
def __str__(self):
return self.title1
I want to show both of them in my home.html
class HomeView(ListView):
model = Post
template_name = 'home.html'
queryset = Post.objects.order_by('-published_date')[:3]
url.py
urlpatterns = [
path('',HomeView.as_view(), name="home"),
path('',PostViewList.as_view(), name="postlist"),
]
I'm new to django and not sure how to show case two model in one template. I did put the post.body and other tags in my html but it not showing the About me part.
Assuming that you want one more queryset of AboutMe model like Post model.
You should simply use get_context_data() in the following way:
class HomeView(ListView):
model = Post
template_name = 'home.html'
queryset = Post.objects.order_by('-published_date')[:3]
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['about_me_records'] = AboutMe.objects.all()
return context
Now, you have one more queryset about_me_records to use in the template and iterate over.
I want to display number of comments on blog home page where all post is showing up. I want to show number of comments on little comment icon under every post is having.
Models:
class BlogPost(models.Model):
sno = models.AutoField(primary_key=True)
title = models.CharField(max_length=60, null=False, blank=False)
body = models.TextField(max_length=5000, null=False, blank=False)
image = models.ImageField(upload_to=upload_location, null=False, blank=True)
date_published = models.DateTimeField(auto_now_add=True, verbose_name="date_published")
date_updated = models.DateTimeField(auto_now=True, verbose_name="date_updated")
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
category = models.CharField(max_length=20, choices=CATEGORIES_NAME, default='Entertainment')
slug = models.SlugField(blank=True, unique=True)
def __str__(self):
return self.title
class BlogComment(models.Model):
sno = models.AutoField(primary_key=True)
comment = models.TextField()
user = models.ForeignKey(Account, on_delete=models.CASCADE)
post = models.ForeignKey(BlogPost, on_delete=models.CASCADE)
timestamp = models.DateTimeField(default=now)
def __str__(self):
return str(self.sno)
Homepage view:
BLOG_POSTS_PER_PAGE = 4
def home_screen_view(request):
context = {}
query = ""
if request.GET:
query = request.GET.get('q', '')
context['query'] = str(query)
blog_posts = sorted(get_blog_queryset(query), key=attrgetter('date_updated'), reverse=True)
comments = BlogComment.objects.all()
# Pagination
page = request.GET.get('page', 1)
blog_posts_paginator = Paginator(blog_posts, BLOG_POSTS_PER_PAGE)
try:
blog_posts =blog_posts_paginator.page(page)
except PageNotAnInteger:
blog_posts =blog_posts_paginator.page(BLOG_POSTS_PER_PAGE)
except EmptyPage:
blog_posts =blog_posts_paginator.page(blog_posts_paginator.num_pages)
context['blog_posts'] = blog_posts
context['comments'] = comments
return render(request, "personal/home.html", context)
I am new to Django and Python. I am trying to create a database of babysitters and one of the objects which can have multiple fields is Education. My first Babysitter has 2 qualifications which produces an error an will not display.
Error Message
views.py
from django.shortcuts import render, get_object_or_404, get_list_or_404
from .models import Babysitter, Education, Work, Reference
# Create your views here.
def all_babysitters(request):
babysitters = Babysitter.objects.all()
return render(request, "babysitters.html", {"babysitters": babysitters})
def babysitter_profile(request, id):
"""A view that displays the profile page of a registered babysitter"""
babysitter = get_object_or_404(Babysitter, id=id)
reference = get_object_or_404(Reference)
education = get_object_or_404(Education)
return render(request, "babysitter_profile.html", {'babysitter': babysitter, 'education': education, 'reference': reference} )
models.py
from django.db import models
from datetime import datetime
# Create your models here.
class Babysitter(models.Model):
list_display = ('firstName', 'lastName', 'minderType')
firstName = models.CharField(max_length=50, blank=True, null=True)
lastName = models.CharField(max_length=50, blank=True, null=True)
minderType = models.CharField(max_length=50, blank=True, null=True)
image = models.ImageField(upload_to='images')
phone = models.CharField(max_length=20, blank=True, null=True)
email = models.CharField(max_length=50, blank=True, null=True)
address1 = models.CharField(max_length=100, null=True)
address2 = models.CharField(max_length=100, null=True)
city = models.CharField(max_length=20, null=True)
county = models.CharField(max_length=100, null=True)
eircode = models.CharField(max_length=7, null=True)
biography = models.TextField(max_length=280,blank=True)
def __str__(self):
return self.firstName + ' ' + self.lastName
class Education(models.Model):
babysitter = models.ForeignKey(Babysitter)
school = models.CharField(max_length=50)
qualification = models.CharField(max_length=50)
fieldOfStudy = models.CharField(max_length=50)
dateFrom = models.DateField(auto_now=False, auto_now_add=False)
dateTo = models.DateField(
auto_now=False, auto_now_add=False, null=True, blank=True)
current = models.BooleanField(default=False)
graduated = models.BooleanField(default=False)
def __str__(self):
return self.school
class Work(models.Model):
babysitter = models.ForeignKey(Babysitter)
family = models.CharField(max_length=50)
role = models.CharField(max_length=50)
location = models.CharField(max_length=50)
dateFrom = models.DateField(auto_now=False, auto_now_add=False)
dateTo = models.DateField(
auto_now=False, auto_now_add=False, null=True, blank=True)
current = models.BooleanField(default=False)
def __str__(self):
return self.work
class Reference(models.Model):
babysitter = models.ForeignKey(Babysitter)
refFamily = models.CharField(max_length=50)
contact = models.CharField(max_length=50)
location = models.CharField(max_length=50)
email = models.CharField(max_length=50, blank=True, null=True)
reference = models.CharField(max_length=300)
date = models.DateField(auto_now=False, auto_now_add=False)
def __str__(self):
return self.refFamily
Can somebody help? I am going to pull my hair out. Thanks
You aren't passing enough information into the calls to get a Reference and Education object:
babysitter = get_object_or_404(Babysitter, id=id)
reference = get_object_or_404(Reference, babysitter_id=babysitter.id)
education = get_object_or_404(Education, babysitter_id=babysitter.id)
The get_object_or_404() function is a shortcut that calls get() underneath, and get() only ever returns a single object (returning more than one will result in the Exception you are seeing).
If you want to see more than one object, then don't use the get_object_or_404 shortcut method (I find those "shortcut" methods to be ugly, personally). Instead, change it to something like:
education_qs = Education.objects.filter(babysitter_id=babysitter.id)
Then loop over that queryset to get the results:
for ed in education_qs:
# Get some data
school = ed.school
You can loop over the queryset in your HTML template, if that's easier.
Update: Here's a better answer that shows how to use querysets:
def babysitter_profile(request, id):
"""A view that displays the profile page of a registered babysitter"""
babysitter = get_object_or_404(Babysitter, id=id)
reference_qs = Reference.objects.filter(babysitter_id=babysitter.id)
education_qs = Education.objects.filter(babysitter_id=babysitter.id)
return render(request, "babysitter_profile.html", {
'babysitter': babysitter,
'education_qs': education_qs,
'reference_qs': reference_qs}
)
Then, in your HTML template, you could do something like the following to show the schools the Babysitter has attended (in a bulleted list):
<ul>
{% for ed in education_qs %}
<li>{{ ed.school }}</li>
{% endfor %}
</ul>
You could do something similar for the Reference data.
I think you should set some parameters to get a specific object, rather than get a bunch of objects.
Just do it like the first instance for get_object_or_404.
reference = get_object_or_404(Reference,id=xx)
education = get_object_or_404(Education,id=yy)
get_object_or_404 returns just 1 object. Use get_list_or_404 if babysitter has "2 qualification" to prevent exception.
babysitter = get_object_or_404(Babysitter, id=id)
education = get_list_or_404(Education, id=babysitter.id)
To prevent MultipleObjectReturned exception.
My problem is have two models job and company and i want to get all jobs in this company
My urls.py:
url(r'^jobs/(?P<slug>[\w-]+)/$', views.job_at_company, name='job_at_company'),
My views.py:
def job_at_company(request, slug):
return render(request, 'jobs.html')
My models.py:
class Company(models.Model):
title = models.CharField(max_length=100, blank=False)
slug = models.SlugField(blank=True, default='')
city = models.CharField(max_length=100, blank=False)
contact_info = models.CharField(max_length=100, blank=False, default=0)
facebook = models.CharField(max_length=100, blank=True)
twitter = models.CharField(max_length=100, blank=True)
linkedin = models.CharField(max_length=100, blank=True)
logo = models.ImageField(upload_to="logo", default=0)
class Jobs(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(blank=True, default='')
company = models.ForeignKey(Company, on_delete=models.CASCADE)
price = models.IntegerField(default='')
Description = models.TextField(blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
job_type = models.CharField(max_length=100, choices=(('Full Time', 'Full Time'),('Part Time', 'Part Time')),default='Full Time')
in the views.py we can add this
def job_at_company(request, slug):
results = Jobs.objects.filter(company__slug=slug)
context = {'items':results}
return render(request, 'jobs.html',context)
Suppose you pass id in the url. The id is the primary key of the company. You would have to modify your url to accept id like -
url(r'^jobs/(?P<slug>[\w-]+)/(?P<pk>[\d]+)$', views.job_at_company, name='job_at_company')
And modify your views.py -
def job_at_company(request, slug, pk):
jobs_qs = Jobs.objects.filter(company__id=pk)
return render(request, 'jobs.html', {'jobs': jobs_qs})
And use it in your html like -
{% for job in jobs %}
{{job.title}}
{% endfor %}
Look at this link. Django's documentation is helpful, follow that
I would like to display only the pictures uploaded by the creator (user) on their individual profiles.
How would I alter my code to display that?
Thank you!
models.py:
class Photo(models.Model):
creator = models.ForeignKey(MyUser, null=False, blank=False)
category = models.ForeignKey("Category", default=1, null=True, blank=True)
title = models.CharField(max_length=30, null=True, blank=True)
description = models.TextField(max_length=120, null=True, blank=True)
image = models.ImageField(upload_to='user/photos/', null=True, blank=True)
slug = models.SlugField(null=False, blank=False)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False, null=True)
updated = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
class Meta:
unique_together = ('slug', 'category')
ordering = ['-timestamp']
def __unicode__(self):
return "%s" %(self.creator)
def get_image_url(self):
return "%s/%s" %(settings.MEDIA_URL, self.image)
def get_absolute_url(self):
return "%s/%s" %(self.creator, self.slug)
views.py:
#login_required
def account_home(request, username):
try:
u = MyUser.objects.get(username=username)
except:
u = None
photo_set = Photo.objects.all()
context = {
"photo_set": photo_set,
"notifications": notifications,
"transactions": transactions
}
return render(request, "accounts/account_home.html", context)
.html:
{% for photo in photo_set %}
<img src="{{ photo.get_image_url }}" class='img-responsive'>
<hr/>
{% endfor %}
You have a ForeignKey to user, so you can just filter the photos by that:
photo_set = Photo.objects.filter(creator=u)
or even better use the reverse relationship:
photo_set = u.photo_set.all()
Also, never ever ever ever use a blank except statement in your code. The only exception you are expecting the get to raise is MyUser.DoesNotExist, so you should catch that only.