django - how to get all the projects for a team? - django

I am new to Django and have a question I couldn't solve it by myself. It is a big question for me.
I want to show the list of Projects related to a specific Team and show it in a ListView.
I would assume it should check the current user belong to which team and then based on the team, it should list the projects.
I have a two apps in my project: 1) users and 2)projects
users.models:
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse
class CustomUser(AbstractUser):
bio= models.CharField(max_length=300, null= True, blank=True)
class Team (models.Model):
title = models.CharField(max_length=200)
user= models.ManyToManyField(get_user_model())
date_created= models.DateTimeField(auto_now_add=True, blank=True, null=True)
date_updated= models.DateTimeField(auto_now=True,blank=True, null=True )
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('team_detail', args=[str(self.pk)])
and the project model is
class Project (models.Model):
team= models.ForeignKey(Team,on_delete=models.CASCADE )
title = models.CharField(max_length=150, null=False, blank=False)
notes = models.TextField( null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True)
date_updated = models.DateTimeField(auto_now=True, blank=True, null=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('project_detail', args=[str(self.pk)])
in projects.views: I made the following codes but cant work out the queryset between two models.
class ProjectPageView(ListView):
model = Project
def get_queryset(self):
queryset = super(ProjectPageView, self).get_queryset()
queryset = queryset.filter( XXXXXXXXXXXXXXX )
return queryset
context_object_name = 'projects_list'
template_name = 'projects/projects.html'
and in the HTML
{% extends '_base.html' %}
{% block title %}Projects{% endblock title %}
{% block content %}
<h1> Project list for this Team : </h1>
{% for project in project_list %}
<div>
<h5>{{ project.title }}</h5>
</div>
{% endfor %}
{% endblock content %}
Really really appreciate your help.

you can get the current user from the request object, then proceed
class ProjectPageView(ListView):
model = Project
def get_queryset(self):
queryset = super(ProjectPageView, self).get_queryset()
user_team = Team.objects.filter(user=self.request.user).first()
queryset = queryset.filter(team=user_team)
return queryset
context_object_name = 'projects_list'
template_name = 'projects/projects.html'

Related

Django - Different user types in a DetailView

I have two user types: Buyer and Merchant and I want to display in a page details of the selected user but a detail view can only use one model
My models
class User(AbstractUser):
is_buyer = models.BooleanField(default=False)
is_merchant = models.BooleanField(default=False)
is_moderator = models.BooleanField(default=False)
pgp = models.CharField(max_length=150, blank=True)
date_created = models.DateTimeField(default=timezone.now)
class Merchant(models.Model): # items
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
def __str__(self):
return f'{self.user.username}'
class Buyer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
pin = models.CharField(max_length=6, blank=True)
def __str__(self):
return f'{self.user.username}'
My views
class ProfileDetailView(DetailView):
model = User
template_name = 'users/profile.html'
slug_field = 'username'
slug_url_kwarg = 'username'
My template and url
{% extends 'base.html' %}
{% block content %}
<article>
<div>
<p>{{ object.pgp }}</p>
</div>
</article>
{% endblock %}
path('profile/<str:username>', usersViews.ProfileDetailView.as_view(), name='user-profile'),
The only thing that seems to work on the template is object.username, if I try using other names it wont show.
What should I do? Create another model Profile? Change my current view or model?
Edit: I created a Profile Model
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
buyer = models.OneToOneField(Buyer, on_delete=models.CASCADE)
merchant = models.OneToOneField(Merchant, on_delete=models.CASCADE)
def __str__(self):
return self.user.username
but then on the view the 2 slug variables
slug_field = 'User.username'
slug_url_kwarg = 'User.username'
raised the error of Generic detail view must be called with either an object pk or a slug
Because there's a one-to-one relationship between the User and Merchant and Buyer, you can access both in your template:
{{ obj.merchant }}
# or
{{ obj.buyer }}
You can then access the properties of Merchant/Buyer:
{{ obj.merchant.some_property }}

Am trying to get individual posts by a particular user. If i click on a particular users i want to get all the posts he has posted Django

Am actually new to programming, so i am just getting a blank page, no errors.
This is my model
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile',
blank=True, null=True)
bio = models.TextField(max_length=500, null=True)
location = models.CharField(max_length=30, null=True)
def __str__(self):
return self.user.username
def get_absolute_url(self):
return reverse('outcome:userprofile-detail', kwargs={'pk': self.pk})
class Post(models.Model):
text = models.TextField(max_length=255)
profile = models.ForeignKey('Profile', null=True, on_delete = models.CASCADE, related_name='create')
overview = models.CharField(max_length=255)
def __str__(self):
return self.text
The view
class Userlist(LoginRequiredMixin, ListView):
model = Profile
template_name = 'outcome/user-list.html'
class UserDetail(LoginRequiredMixin, DetailView):
model = Profile
template_name = 'outcome/userprofile_detail.html'
The template
{% for i in post.profile_set.all %}
**`trying to loop over the post`**
{{i.text}}
{% endfor %}
I have tried this for a while now and i dont know whether its from template or view.
You can override get_context_data method like this :
class UserDetail(LoginRequiredMixin, DetailView):
model = Profile
template_name = 'outcome/userprofile_detail.html'
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 the user posts
all_posts = Post.objects.all()
user_posts = all_posts.filter(profile_id=self.request.user.profile.id)
context['user_posts'] = user_posts
return context
user_detail.html
{% for post in user_posts %}
{{post.text}}
{{post.overview}}
{% endfor %}

for loop doesn't work in Django template (inside of table tag)

i'm trying to create a table inside of my html template,
but when i write <td>{{project.title}}</td> it doesn't work!
actually when i use {{x}} i have no output!
i don't really know what's wrong inside of my template...
html template:
{% extends 'main.html' %}
{% block content %}
<h1>Projects</h1>
<table>
<tr>
<th>ID</th>
<th>Project</th>
<th>Votes</th>
<th>Ratio</th>
<th></th>
</tr>
{% for project in Projects %}
<tr>
<td>{{project.id}}</td>
<td>{{project.title}}</td>
<td>{{project.vote_total}}</td>
<td>{{project.vote_ratio}}</td>
<td>{{project.created}}</td>
<td>View</td>
</tr>
{% endfor %}
</table>
{% endblock content %}
models.py:
from django.db import models
import uuid
from django.db.models.deletion import CASCADE
# Create your models here.
class Project(models.Model):
title = models.CharField(max_length=200)
descripeion = models.TextField(null=True, blank=True)
demo_link = models.CharField(max_length=1000, null=True, blank=True)
source_link = models.CharField(max_length=1000, null=True, blank=True)
tags = models.ManyToManyField('Tag', blank=True)
vote_total = models.IntegerField(default=0, null=True, blank=True)
vote_ratio = models.IntegerField(default=0, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True,
editable=False)
def __str__(self) -> str:
return self.title
class Review(models.Model):
VOTE_TYPE = (
('up', 'Up Vote'),
('down', 'Down Vote')
)
# owner =
project = models.ForeignKey(Project, on_delete=CASCADE)
body = models.TextField(null=True, blank=True)
value = models.CharField(max_length=200, choices=VOTE_TYPE)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True,
editable=False)
def __str__(self) -> str:
return self.value
class Tag(models.Model):
name = models.CharField(max_length=200)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True,
editable=False)
def __str__(self) -> str:
return self.name
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from .models import Project
projectsList = [
{
'id':'1',
'title':'Ecommerce Website',
'description':'Fully functional ecommerce website'
},
{
'id':'2',
'title':'Portfolio Website',
'description':'This was a project where i built out my
portfolio'
},
{
'id':'3',
'title':'Social network',
'description':'owesome open source project i am still
working'
},
]
def projects(request):
projects = Project.objects.all()
context = {'projects': projects}
return render(request, 'projects/projects.html',context)
def project(request, pk):
projectObj = Project.objects.get(id=pk)
return render(request, 'projects/single-project.html',
{'project': projectObj})
admin.py:
from django.contrib import admin
from .models import Project, Review, Tag
admin.site.register(Project)
admin.site.register(Review)
admin.site.register(Tag)
the files and folders
Anyone know what I am doing wrong here?
As you are passing projects in context processor with small case "p" , Make it as
{% for project in projects %}
in your template.

django (1.11) manytomanyfield templatetags filter

The task is this: There are doctors, there are specializations. A doctor can have several specializations. It is necessary to draw a conclusion of the list of Doctors by specialization.
Model:
class Doctor(models.Model):
title = models.CharField(max_length=200, verbose_name='Имя')
slug = models.SlugField(unique=True)
image = models.ImageField(null=True, blank=True, verbose_name='Фото')
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True, verbose_name='Создано')
special = models.ManyToManyField('Specialization')
experience= models.CharField(max_length=200, verbose_name='Стаж', blank=True)
category = models.CharField(max_length=200, verbose_name='Категория', blank=True)
content = RedactorField(verbose_name='Контент')
keywords = models.CharField(max_length=1024, blank=True, null=True)
description = models.CharField(max_length=1024, blank=True, null=True)
class Meta:
verbose_name = 'Врача'
verbose_name_plural = 'Врачи'
def __str__(self): # For Python 2, use __unicode__ too
return self.slug
def get_absolute_url(self):
return reverse('show_doctor', kwargs={'slug': self.slug})
class Specialization(models.Model):
name = models.CharField(max_length=200, verbose_name='Название')
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True, verbose_name='Создано')
class Meta:
verbose_name = 'Специализацию'
verbose_name_plural = 'Специализации'
def __str__(self): # For Python 2, use __unicode__ too
return self.name
Templatetags:
from django import template
from doctor.models import Doctor, Specialization
register = template.Library()
#register.inclusion_tag('doctors_list.html')
def get_doctors_list(request):
special_list = Specialization.objects.all()
return {
'doctors_list': Doctor.objects.filter(special=special_list),
'spec_list': special_list
}
HTML Template:
{% for s in spec_list %}
<h3>{{ s.name }}</h3>
<ul>
{% for d in doctors_list %}
<li>{{ d.title }}</li>
{% endfor %}
</ul>
{% endfor %}
Should be: PrtSc . I can not figure it out, help me)
You are going about Django in a totally wrong way when you use a template tag for this purpose. Data is passed to the template through context variables. In your case you nedd a ListView over a Specialization queryset. You should access the doctors through the reverse relation in the Specialization model (doctor_set). Do add a prefetch_related for that value to the queryset too.

Django: Template logic not rendering query data, no errors given either

I have a template based view that doesn't seem to be working(or atleast doesnt seem to be working on the page that needs to render it).
Here is the View:
class LocationManager(View):
template_name = "dash/LocationManager.html"
def get(self, request, *args, **kwargs):
try:
user = User.objects.get(username=request.user.username)
locations = user.get_profile().owned_locations
return render(request, self.template_name, {'locations': locations})
except:
return render(request, self.template_name)
Here are the models that have to do with this view:
#in Location models
class Location(models.Model):
region = models.ForeignKey(Region)
manager = models.ForeignKey(User)
name = models.CharField(max_length=255)
street_address = models.TextField(blank=True)
city = models.CharField(max_length=255, blank=True)
zip_code = models.CharField(max_length=20, blank=True)
#in UserProfile models
class UserProfile(models.Model):
user = models.OneToOneField(User)
api_key = models.TextField()
pp_api_key = models.TextField(blank=True)
owned_beacons = models.ManyToManyField(
Beacon,
blank=True,
null=True,
related_name='owned_beacons'
)
owned_locations = models.ManyToManyField(
Location,
blank=True,
null=True,
related_name='owned_locations'
)
def __unicode__(self):
return u'%s' % self.user.username
And finally the template:
{% for location in locations.all %}<tr>
<td>{{location.name}}</td>
<td>{{location.street_address}}</td>
<td>{{location.zip_code}}</td>
<td>{{location.region}}
</tr>
{% endfor %}
Yet the template does not render anything in relation to the form logic(the rest of the template loads fine). No errors are raised either which is why this is making it hard for me to understand why the template logic/view isn't working properly. Any ideas would be really helpful.
Try {% for location in locations %}