'model' object has no attribute 'object' - error in Django? - django

I get this error:
'Searches' object has no attribute 'object'. I am using the generic ListView and I iterate over object_list in template. That is where the error comes in. My view is simple. Just attaching the model. All the relevant code is here.
Thanks
urlpatterns:
urlpatterns = patterns('',
url(r'^create/$','customsearches.views.create_search' , name='create_search'),
url(r'^list/$', SearchListView.as_view(template_name='search_list.html'), name='search_list'),
)
my model:
class Searches(models.Model):
SELLER_CHOICES=(('OWNER','owner'),
('DEALER','dealer'),
('BOTH','both'), )
#search_id = models.IntegerField(primary_key=True)
user = models.ForeignKey(User)
make = models.CharField(max_length=100, blank=True)
model = models.CharField(max_length=100, blank=True)
keywords = models.CharField(max_length=100, blank=True)
max_price = models.IntegerField(blank=True, null=True)
min_price = models.IntegerField(blank=True, null=True)
max_year = models.IntegerField(blank=True, null=True)
min_year = models.IntegerField(blank=True, null=True)
pic_only = models.NullBooleanField()
search_title_only = models.NullBooleanField()
owner_dealer_all = models.CharField(max_length=10,choices=SELLER_CHOICES,verbose_name='owner/dealer')
class Meta:
#managed = False
db_table = 'Searches'
verbose_name_plural = "Searches"
def __unicode__(self):
return "%s %s %s-%s" %(self.make,self.model,self.max_year,self.min_year)
def get_absolute_url(self):
return reverse('postings.views.detail',args=[model_to_dict(self.object)])
view:
class SearchListView(ListView):
model=Searches
template:
{% extends "base.html" %}
{% block content %}
{% for obj in object_list %}
<p>{{ obj }}</p>
{% endfor %}
{% endblock %}

The problem is on the line:
return reverse('postings.views.detail',args=[model_to_dict(self.object)])
Searches model doesn't really have an object attribute.
model_to_dict() needs a model instance:
model_to_dict(self)
Hope that helps.

Related

Django render many to many in template

I have this models:
class roles(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=255, blank=False)
company = models.ForeignKey(Company, blank=True, null=True, on_delete=models.SET_NULL)
def __str__(self):
return self.name
class freelancers(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
company = models.ForeignKey(Company, blank=True, null=True, on_delete=models.SET_NULL)
user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)
role = models.ManyToManyField(roles)
I try to get the name that is related to the user at the roles table.
In my view.py It looks like this:
def company_details(request,id):
obj = Company.objects.get(id=id)
pro = Projects.objects.filter(company=id)
free = freelancers.objects.filter(company=id)
#free = freelancers.objects.all()
return render(request, 'company/company_details.html',
{
'obj':obj,
'pro':pro,
'free':free,
}
)
And in the HTML:
{% for f in free %}
{{ f.user }} // <br/>
{% endfor %}
{{ f.role.all }}
{% endfor %}
I have been trying different ways to get the name to show up.
Like: {{ f.role.name }}.
So any tips to make this work?
I think you will have to iterate through the f.role.all

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

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'

Filter product_set in django-mptt

Have 2 models
class Category(MPTTModel):
title = models.CharField()
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
class Product(models.Model):
category = models.ForeignKey(Category, blank=True, null=True)
I want to get tree from both models.
Now i can get:
in views
nodes = Category.objects.all()
in template
{% for n in nodes %}
{% for t in n.product_set.all %}
But i want to get
nodes = Category.objects.all().**insert_to_category_product_with_filter**(id__in=[list_id])
I found only one solution via template_tag
#register.filter()
def filter_GET(node, GET):
qs = node.product_set.all().prefetch_related('product_set')
product = GET.get('product', None)
if product:
qs = qs.filter(product_id=product)
any_more = GET.get('any_more', None)
return qs
in template
{% for n in node|filter_GET:request.GET %}

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.

Display ForeignKey attributes in template

I have the following models:
# models.py
class Site(models.Model):
name = models.CharField(max_length=75)
slug = models.SlugField(_('slug'), max_length=75, blank=True, null=True)
link = models.CharField(max_length=150)
created_on = models.DateTimeField(auto_now_add=True, editable=False)
modified_on = models.DateTimeField(auto_now=True)
class SiteRatings(models.Model):
site = models.ForeignKey('Site', related_name='siterating', blank=True, null=True)
overall_rating = models.FloatField(blank=True, null=True)
plans_rating = models.FloatField(blank=True, null=True)
prices_rating = models.FloatField(blank=True, null=True)
design_rating = models.FloatField(blank=True, null=True)
support_rating = models.FloatField(blank=True, null=True)
def save(self, *args, **kwargs):
self.overall_rating = (self.plans_rating + self.prices_rating + self.design_rating + self.support_rating)/4
super(SiteRatings, self).save(*args, **kwargs)
def __str__(self):
return self.site.name
My views
# views.py
def home(request):
print(user_language)
site_list = Site.objects.order_by('-date_launched')
return render_to_response('index.html', {'site_list': site_list}, RequestContext(request))
In template
# template
{% for site in site_list %}
<h4><span class="label label-info">{{ site.name }}</span></h4>
<h4><span class="label label-info">{{ site.siterating.overall_rating }}</span></h4>
{% endfor % }
The problem is that when I try to access {{ site.siterating.overall_rating }} nothing is being returned, I tried to change for {{ site.siterating.0.overall_rating }} and it is not displaying yet.
I solved my problem. First in models I created a method to get the site rating (thank you karthikr for your suggestion):
#models
class Site(models.Model):
name = models.CharField(max_length=75)
slug = models.SlugField(_('slug'), max_length=75, blank=True, null=True)
link = models.CharField(max_length=150)
created_on = models.DateTimeField(auto_now_add=True, editable=False)
modified_on = models.DateTimeField(auto_now=True)
def get_site_rating(self):
return self.siterating.filter(site = self)
After, I went to my template and used the class method that I had created:
{% for site in site_list %}
<h4><span class="label label-info">{{ site.name }}</span></h4>
<h4><span class="label label-info">{{ site.get_site_rating.0.overall_rating }}</span></h4>
{% endfor % }
Please, note that I used ...get_site_rating.0... just because in my case I have just 1 rating/site.