Detailview Object Relations - django

;TLDR - After some solutions discovered, my final question is how can I, if at all, access models related to models related to the main detailview model?
I'm trying to use a generic detailview to return an object and it's related object. In this example, a company like mcdonalds would have any sites (or locations). What I want the detailview to be able to show is the company detail, and the site detail related to the company. I'm stuck though. Dispite my efforts in not asking for help, I have not been able to pull the data from the model referencing the company sites. Where am I going wrong? I have sort of proven this to work in the django shell with SiteModel.objects.filter(company=5) showing all of the company with an ID of 5's site names.
models.py
'''
The company model consists of the base company information
'''
class CompanyModel(models.Model):
name = models.CharField(_('Company Name'), max_length=255, blank=False)
website = models.URLField(_('Company Website'), blank=True)
since = models.DateField(auto_now_add=True)
rate = models.DecimalField(max_digits=5, decimal_places=2, blank=False)
def __str__(self):
return '%s' % (self.name)
class Meta:
ordering = ['name']
verbose_name = 'Company'
verbose_name_plural = 'Companies'
'''
The site model consists of sites of a company as
some companies have several sites that we will work from.
'''
class SiteModel(models.Model):
company = models.ForeignKey(CompanyModel, on_delete=models.PROTECT)
address = models.ForeignKey(AddressModel, on_delete=models.PROTECT)
phone = models.ForeignKey(PhoneModel, blank=True, null=True, on_delete=models.PROTECT)
distance = models.SmallIntegerField(blank=True)
def __str__(self):
return '%s - %s, %s' % (self.company, self.address.city, self.address.state)
class Meta:
ordering = ['company']
verbose_name = 'Company Site Information'
verbose_name_plural = 'Company Sites'
views.py
class CompanyDetailView(DetailView):
model = CompanyModel
template_name = 'customers/detail.html'
def get_context_data(self, **kwargs):
context = super(CompanyDetailView, self).get_context_data(**kwargs)
context['sites'] = SiteModel.objects.filter(id=self.kwargs['pk'])
return context
urls.py
url(r'^customer/(?P<pk>[0-9a-z-]+)/detail/$', CompanyDetailView.as_view(),
name='customer-detail'),
Update 1:
My template is showing the correct company, but only 1 site, and the site is not related to the company. Arg. It's showing both the company who's ID is 5, and the site who's ID is 5. How do I connect the dots correctly here?
template
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Customer Detail</title>
</head>
<body>
<div class="container">
{{ object.name }}
{% for site in sites %}
{{ site }}
{% endfor %}
</div>
</body>
</html>
Update 2:
I was able to sort this out by not supering get_context_data, and just itterating through the _set suffix of the related model's name. Django Documentation Reference
template
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Customer Detail</title>
</head>
<body>
<div class="container">
{{ company.name }}
{% for site in company.sites.all %}
{{ site }}
{% endfor %}
</div>
</body>
</html>
The follow up to this, however, is how do I go more than one layer deep? Following up with the above models, I also have a "reports" model. But when I use the same method as above, it seems to break down after the first model. i.e. I can't just use company.sites.reports.
models.py
class ServiceReportModel(models.Model):
report_number = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
site = models.ForeignKey(customers_models.SiteModel, on_delete=models.PROTECT, related_name='reports')
request_number = models.ForeignKey(ServiceRequestModel,
on_delete=models.PROTECT,
null=True,
blank=True,
related_name='s_report_number'
)
reported_by = models.ForeignKey(main_models.MyUser, related_name='reports')
reported_date = models.DateTimeField(auto_now_add=True)
updated_by = models.ForeignKey(main_models.MyUser, blank=True, null=True, related_name='+')
updated_date = models.DateTimeField(auto_now=True)
equipment = models.ForeignKey(customers_models.EquipmentModel, on_delete=models.PROTECT)
report_reason = models.CharField(max_length=255, null=True)
time_in = models.DateTimeField(blank=True, null=True)
time_out = models.DateTimeField(blank=True, null=True)
actions_taken = models.TextField(null=False, blank=False)
recommendations = models.TextField(null=True, blank=True)
def get_absolute_url(self):
return reverse('service-report', kwargs={'pk': self.pk})
def __str__(self):
return '%s - %s, %s' % (self.site.company, self.reported_date.strftime('%d %B %Y'), self.equipment.name)
class Meta:
ordering = ['reported_date']
verbose_name = 'Service Report'
verbose_name_plural = 'Service Reports'

I was able to get a solution with some help. I went back to super'ing the get_context_data method, and following this documentation regarding spanning relationships using filters and double underscore notation.
class CompanyDetailView(DetailView):
model = CompanyModel
context_object_name = 'company'
template_name = 'customers/detail.html'
def get_context_data(self, **kwargs):
context = super(CompanyDetailView, self).get_context_data(**kwargs)
context['sites'] = SiteModel.objects.filter(company=self.get_object())
context['reports'] = ServiceReportModel.objects.filter(site__company=self.get_object())
return context

Related

when I try to render tags I get Wallpaper.Wallpaper.None

views.py
def download(request, wallpaper_name):
try:
wallpaper = Wallpaper.objects.get(name=wallpaper_name)
similar_wallpapers = wallpaper.tags.similar_objects()[:2]
except Exception as exc:
wallpaper = None
similar_wallpapers = None
messages.error = (request, 'Sorry! data does not exist')
context = {'wallpaper': wallpaper, 'similar_wallpapers': similar_wallpapers}
return render(request, 'Wallpaper/download.html', context)
models.py
class Tags(models.Model):
tag = models.CharField(max_length=100)
def __str__(self):
return self.tag
class Wallpaper(models.Model):
name = models.CharField(max_length=100, null=True)
size = models.CharField(max_length=50, null=True)
pub_date = models.DateField('date published', null=True)
resolution = models.CharField(max_length=100, null=True)
category = models.ManyToManyField(Category)
tags = TaggableManager()
Device_Choices = [
('PC', 'pc'),
('mobile', 'mobile')
]
Devices = models.CharField(max_length=20,choices=Device_Choices, default= 'PC')
image = models.ImageField(upload_to='Wallpaper/Images/', default="")
def __str__(self):
return self.name
download.html
<div class="tag">
<h3>Tags</h3>
<ul>
<li>{{wallpaper.tags}}</li>
</ul>
</div>
I want all the tags of that particular wallpaper to be rendered
and if possible please tell me if there is any other way to handle tags, because using taggit its very difficult i am getting manny errors
Tags are a many-to-many relation so you need to use .all in your template to get them. However, this will just show you the queryset, so you need to loop through them to render their names:
<ul>
{% for tag in wallpaper.tags.all %}
<li>{{ tag.name }}</li>
{% endfor %}
</ul>

How to get the previous and next related post in django?

views.py
def post_details(request,pk):
post = Post.objects.get(id=pk)
# next_post = Post.objects.filter(id=pk)
context={'post':post,'next':next_post}
return render(request, 'blog/post_detail.html', context)
blog-detail
<div class="s-content__pagenav group">
<div class="prev-nav">
<a href="#" rel="prev">
<span>Previous</span>
Tips on Minimalist Design
</a>
</div>
<div class="next-nav">
<a href="#" rel="next">
<span>Next</span>
Less Is More
</a>
</div>
</div>
models
# this is my model
class User(AbstractUser):
# pass
name = models.CharField(max_length=200)
bio = models.TextField(null=True)
email = models.EmailField(unique=True, null=True)
avatar = models.ImageField( null=True, upload_to='blog_media', default="images/avatar.svg")
facebook = models.URLField(blank=True, null=True)
twitter = models.URLField(blank=True, null=True)
dribbble = models.URLField(blank=True, null=True)
instagram = models.URLField(blank=True, null=True)
class Category(models.Model):
name = models.CharField(max_length=20)
class Meta:
verbose_name = 'Category'
verbose_name_plural = 'Categories'
def __str__(self):
return self.name
class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.ManyToManyField(Category)
title = models.CharField(max_length=200, blank=False);
description = models.TextField(null=True,blank=True)
image = models.ImageField(upload_to='blog_media')
url = models.URLField(null=True, blank=True)
body = HTMLField()
created = models.DateTimeField(auto_now=True)
updated = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Based on your comments, I'm assuming that you would like to get two related posts that have the same category as the current post.
If I'm correct, then one method you could use is to filter the queryset for the same category belonging to the current post then you could choose the next and previous posts of the current post from the retrieved queryset. For example:
def post_details(request, pk):
current_post = Post.objects.get(pk=pk) # retrieving the current post...
# filtering for related posts only by using the category of the current post
# using -> category_in=post.category.all() since it's a ManyToMany field
related_posts = Post.objects.filter(category_in=current_post.category.all())
# next -> get posts with id greater than the current post id, then get the first instance 'next post'
# previous -> get posts with id less than the current post id, then get the first instance 'previous post'
context = {
'post': current_post,
'next': related_posts.filter(id__gt=current_post.id).order_by('id').first(),
'previous': related_posts.filter(id__lt=current_post.id).order_by('-id').first()
}
return render(request, 'blog/post_detail.html', context)
Ideally, that should work.
A quick recommendation here as well... Instead of using Post.objects.get(pk=pk), I'd suggest using get_object_or_404() as this will handle any potential error that Post.objects.get(pk=pk) will throw. So a small update...
from django.shortcuts import get_object_or_404
def post_details(request, pk):
current_post = get_object_or_404(Post, pk=pk) # retrieving the current post...
# the rest of the code follows...

Trying to delete a comment from a post in django

I am currently trying to delete a comment from my database via a button in django template.
Model looks like this
from django.db import models
from django.contrib.auth.models import User
from cloudinary.models import CloudinaryField
from profiles.models import UserProfile
class Post(models.Model):
user_profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, related_name='user_posts')
title = models.CharField(max_length=220, unique=True)
location = models.CharField(max_length=220)
rating = models.DecimalField(
max_digits=6, decimal_places=2)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="activity_post")
updated_on = models.DateTimeField(auto_now=True)
description = models.TextField()
featured_image = CloudinaryField('image', blank=False)
created_on = models.DateTimeField(auto_now_add=True)
likes = models.ManyToManyField(User, related_name='activity_likes', blank=True)
like_count = models.BigIntegerField(default='0')
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
def number_of_likes(self):
return self.likes.count()
def liked_by_user(self):
return self.likes.values_list('id', flat=True)
class Comment(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="user_comment")
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['created_on']
def __str__(self):
return f"Comment {self.body} by {self.name}"
Delete function
def delete_comment(request, post_id):
users_comment = get_object_or_404(Comment, post=post_id)
users_comment.delete()
return redirect(reverse('activity'))
URLS
from . import views
from django.urls import path
urlpatterns = [
path('like/', views.like, name='like'),
path("add/", views.add_post, name="add_post"),
path('edit/<int:post_id>/', views.edit_post, name='edit_post'),
path('delete/<int:post_id>/', views.delete_post, name='delete_post'),
path('edit_comment/<int:id>/', views.edit_comment, name='edit_comment'),
path('delete_comment/<int:post_id>/', views.delete_comment, name='delete_comment'),
path("activity/", views.PostList.as_view(), name="activity"),
path('comment/<int:post_id>/', views.Comment.as_view(), name='comment'),
path('searched_posts/', views.search_posts, name='searched_posts'),
path('post/<int:post_id>/', views.post_detail, name='post_detail')
]
here is the comment part that is showing the button.
{%if comments %}
{% for comment in comments %}
{% if comment.user == request.user %}
{{comment.body}} :comment
{{comment.id}} id
<a class="btn tbn-success" href="{% url 'edit_comment' comment.id %}" aria-label="edit button">Edit</a>
<button class="btn btn-warning">Delete</button>
{% endif %}
{% endfor%}
{% endif%}
When I click delete i get an error
Error
Any help would be greatly appreciated, I have tried a ton of different ways from online but nothing seems to work. can anyone point me in the right direction
The first thing I can see is that your delete function uses post = post_id.
Every comment on a particular post will share that post foreign key, so if there is more than one comment on a post, you can't use get_or_404() - it's limited to returning 1 item.
The URL you create for your button is using comment.id so it makes sense to use that instead - this will make it easier to see what's happening.
urls.py
path('delete_comment/<int:comment_id>/', views.delete_comment, name='delete_comment'),
views.py
def delete_comment(request, comment_id):
users_comment = get_object_or_404(Comment, pk=comment_id)
users_comment.delete()
return redirect(reverse('activity'))

Template not showing context variable

I created an app called marketing app which customizes messages to be written on top of home page. My problem is that these messages are not showing when everything configured and I don't know why is that might be the template because {{ marketing_message.message }} is only not showing
This is the model:
class MarketingMessage(models.Model):
message = models.CharField(max_length=120)
active = models.BooleanField(default=False)
featured = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
start_date = models.DateTimeField(
auto_now_add=False, auto_now=False, null=True, blank=True)
end = models.DateTimeField(
auto_now_add=False, auto_now=False, null=True, blank=True)
def __str__(self):
return str(self.message[:12])
This is the view:
from marketing.models import MarketingMessage
class HomeView(ListView):
model = Item
paginate_by = 10
template_name = "home.html"
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
context['marketing_message'] = MarketingMessage.objects.all()
return context
This is the template:
{% if marketing_message %}
<div id="top-alert"class="alert alert-light" style="padding-top:85px; margin-bottom:-24px;">
×
<div class="container" style="text-align:center">
<strong> Marketing Message ! : </strong> {{ marketing_message.message}}
</div>
</div>
{% endif %}
marketing_message is a QuerySet, not a model instance.
You probably only want the most recent "active" message.
context['marketing_message'] = MarketingMessage.objects.filter(active=True).latest('timestamp')
Or the most recently updated:
context['marketing_message'] = MarketingMessage.objects.filter(active=True).latest('updated')
However latest() will fail if there is no object, which is likely not what you want, but you can do this:
try:
context['marketing_message'] = MarketingMessage.objects.filter(active=True).latest('updated')
except MarketingMessage.DoesNotExist:
context['marketing_message'] = None
Looking at your data, though, it seems incorrect. You have a start and end dates, but also active. You can imply if something is active if it falls within the start and end dates.
Also, since you have this, it seems like you could have multiple messages at once, in which case you should drop the .latest() and iterate over the ones within the start and end dates.

Retrieve a user list from a manydomanyfield with information from an intermediate table

it's been a few hours since I tried to retrieve a list of users with the information of an intermediate table.
So I have a workspace model that is a manytomanyfield with users
There is also an intermediary table to differentiate the classic users and the workspace manager
I would like to display the list of users and add a small icon symbolizing the managers in the list.
But unfortunately it seems difficult for Django, to display both the list of users of the workspace with the information of the intermediate table.
In any case I look at the documentation of Django I have not managed to find how to do.
models.py
class Workspace(models.Model):
name = models.CharField(max_length=250, verbose_name="Nom du workspace")
members = models.ManyToManyField(User, through='Membership', verbose_name="Membres du workspace")
token = models.CharField(max_length=500) # token statique
join_token = models.CharField(max_length=500) # token dynamique
join_token_date = models.DateTimeField(auto_now_add=False, null=True, blank=True)
payday = models.DateField(max_length=10, verbose_name="Jour de paye", null=True, blank=True)
planning_image = ProcessedImageField(upload_to='planning',
null=True,
blank=True,
processors=[ResizeToFill(1299, 937)],
format='JPEG',
options={'quality': 100})
planning_thumbnail = ImageSpecField(source='planning_image',
processors=[ResizeToFill(280, 202)],
format='JPEG',
options={'quality': 100})
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('create-workspace')
class Membership(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
workspace = models.ForeignKey(Workspace, on_delete=models.CASCADE)
is_manager = models.BooleanField(default=False)
date_joined = models.DateTimeField(auto_now_add=True)
views.py
#login_required
def workspace_detail(request, token):
ins_workspace = get_object_or_404(Workspace, token=token)
list_members = ins_workspace.members.all()
for member in list_members:
if member == request.user:
current_user = Membership.objects.get(workspace=ins_workspace, user=request.user)
context = {
'name': ins_workspace.name,
'token': ins_workspace.token,
'list_members': list_members,
'payday': ins_workspace.payday,
'is_manager': current_user.is_manager,
}
return render(request, 'workspace/workspace_detail.html', context)
else:
return HttpResponseForbidden()
template.html
{% for item in list_members %}
{{ item.username }}
{% endfor %}
This is what I want:
template.html
{% for item in list_members %}
{% item.is_manager %}
{{ item.username }} (♔)
{% else %}
{{ item.username }}
{% endfor %}
You can do it like this:
Update Membership model with related name:
class Membership(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="membership")
workspace = models.ForeignKey(Workspace, on_delete=models.CASCADE)
is_manager = models.BooleanField(default=False)
date_joined = models.DateTimeField(auto_now_add=True)
Then you can update your view like following:
from django.db.models import F
#login_required
def workspace_detail(request, token):
ins_workspace = get_object_or_404(Workspace, token=token)
list_members = ins_workspace.members.all().annotate(is_manager=F('membership__is_manager'))
context = {
'name': ins_workspace.name,
'token': ins_workspace.token,
'list_members': list_members,
'payday': ins_workspace.payday,
'is_manager': request.user.membership.get(workspace=ins_workspace).is_manager,
}
return render(request, 'workspace/workspace_detail.html', context)
That should do the trick.
Here what I have done is that, I am using a reverse relation to get is_manager value from membership model. I am annotating that value in the queryset using F.