Problem inheriting get_absolute_url in an child model - django

I have the following sets of models (abbreviated for clarity):
First set:
class Web(Link):
ideas = models.ManyToManyField(Idea, blank=True, null=True)
precedents = models.ManyToManyField(Precedent, blank=True, null=True)
categories = GenericRelation(CategoryItem)
#permalink
def get_absolute_url(self):
return ('resources-link-detail', [str(self.slug)])
which is a child of:
class Link(models.Model):
title = models.CharField(max_length=250)
description = models.TextField(blank=True)
website = models.URLField(unique=True)
slug = models.SlugField(unique_for_date='pub_date')
...
#permalink
def get_absolute_url(self):
return ('link-detail', [str(self.slug)])
Second set
class ResourceOrganization(Organization):
ideas = models.ManyToManyField(Idea, blank=True, null=True)
precedents = models.ManyToManyField(Precedent, blank=True, null=True)
categories = GenericRelation(CategoryItem)
#permalink
def get_absolute_url(self):
return ('resources-org-detail', [str(self.slug)])
which is a child of:
class Organization(Contact):
name = models.CharField(max_length=100)
org_type = models.PositiveSmallIntegerField(choices=ORG_CHOICES)
...
#permalink
def get_absolute_url(self):
return ('org-detail', [str(self.slug)])
which is a child of:
class Contact(models.Model):
description = models.TextField(blank=True, null=True)
address_line1 = models.CharField(max_length=250, blank=True)
address_line2 = models.CharField(max_length=250, blank=True)
slug = models.SlugField(unique=True)
...
class Meta:
abstract = True
The "ResourceOrganization" model is properly overiding the get_absolute_url method and is adding the "categories" generic relation.
The "Web" model is not.
I'm at a loss to figure out why. Would appreciate any insight.
P.S. I'm realizing that there may have been better ways to implement this functionality, but I'm stuck with it for the moment until I can refactor and would like to get it working.
Thanks.

If anyone else is running into this problem, take a look at any custom managers you have defined on the parent model. They will not inherit to the child model in the way you might think.
http://docs.djangoproject.com/en/dev/topics/db/managers/#custom-managers-and-model-inheritance

Related

cannot display classes of courses

I am trying to create an educational website using django, so I have two models class and course which have a one-to-many foreignkey relationship between them i.e. one course can have several class but one class can only have one course. But this creates a problem for me. That is, in my course_detail_view I have assigned the model course. So I cannot render classes in my html file. Can anyone help me solve this ?
My models.py:
class Course(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='class/instructor_pics', null=True)
instructor = models.CharField(max_length=100)
instructor_image = models.ImageField(upload_to='class/instructor_pics', null=True)
students = models.ManyToManyField(User, related_name='courses_joined', blank=True)
slug = models.SlugField(max_length=200, unique=True)
description = models.TextField(max_length=300, null=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created']
def __str__(self):
return self.title
class Class(models.Model):
title = models.CharField(max_length=100)
video = models.FileField(upload_to='class/class_videos',null=True,
validators=[FileExtensionValidator(allowed_extensions=['MOV','avi','mp4','webm','mkv'])])
course = models.ForeignKey(Course, on_delete=models.CASCADE, null=True, related_name='classes')
def __str__(self):
return self.title
My views.py:
class CourseDetailView(LoginRequiredMixin, DetailView):
model = Course
template_name = 'class/course.html'
Thanks in advance!

calling a class inside another class function

I am trying to create an educational website using django so I have a class model and a course model. I have tried to use the Many-to-one foreignkey relationship but that doesn't work, I can create classes using foreignkey but that class is not being assigned to that course only. It appears in other courses as well. So how can I make this work? What should I change?
My models.py:
class Class(models.Model):
title = models.CharField(max_length=100)
video = models.FileField(upload_to='class/class_videos',null=True,
validators=[FileExtensionValidator(allowed_extensions=['MOV','avi','mp4','webm','mkv'])])
def __str__(self):
return self.title
class Course(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='class/instructor_pics', null=True)
instructor = models.CharField(max_length=100)
instructor_image = models.ImageField(upload_to='class/instructor_pics', null=True)
students = models.ManyToManyField(User, related_name='courses_joined', blank=True)
classes = models.ForeignKey(Class, on_delete=models.CASCADE, null=True)
slug = models.SlugField(max_length=200, unique=True)
description = models.TextField(max_length=300, null=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created']
def __str__(self):
return self.title
You are using the foreign key in the wrong model. If each class can only have one course, but a single course, can have multiple classes, you should place the ForeignKey in the class model instead of the course model. Your code would be like this:
class Course(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='class/instructor_pics', null=True)
instructor = models.CharField(max_length=100)
instructor_image = models.ImageField(upload_to='class/instructor_pics', null=True)
students = models.ManyToManyField(User, related_name='courses_joined', blank=True)
slug = models.SlugField(max_length=200, unique=True)
description = models.TextField(max_length=300, null=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created']
def __str__(self):
return self.title
class Class(models.Model):
title = models.CharField(max_length=100)
video = models.FileField(upload_to='class/class_videos',null=True,
validators=[FileExtensionValidator(allowed_extensions=['MOV','avi','mp4','webm','mkv'])])
course = models.ForeignKey(Course, on_delete=models.CASCADE, null=True, related_name='classes')
def __str__(self):
return self.title
And when you want to list the classes of a single course, you can use this code (you should use the related_name field in the source model like the way I have used in the class model):
course = Course.objects.filter(some_filter=some_value).first()
course.classes.first() # This will return the first class of the course

Django Admin, show inline based on slug

Have the following models
class FootballWebsite(models.Model):
"""Football service website."""
url = models.URLField, unique=True)
#football service
id = models.CharField(primary_key=True,
#is this domain blocked
blocked = models.BooleanField(default=False)
#is it online or offline
online = models.BooleanField(default=False)
updated = models.DateTimeField(auto_now=True, auto_now_add=True)
sub_categories = models.ForeignKey(SubCategory, default=1)
referral = models.TextField(blank=True)
mirror = models.ForeignKey('FootballWebsite', blank=True, null=True)
rank = models.PositiveIntegerField(default=0, blank=True, null=True)
screenshot = models.BooleanField(default=False)
class Meta:
"""Meta class."""
app_label = 'ahmia'
def __unicode__(self):
return u'%s' % (self.url)
"""The datetime when the football service was last seen online"""
try:
return self.footballwebsitestatus_set.filter(online=True).latest('time').time
except FootballWebsiteStatus.DoesNotExist:
return None
class FootballWebsiteDescription(models.Model):
"""Football service website description."""
about = models.ForeignKey(Footballebsite)
title = models.TextField(blank=True, null=True)
keywords = models.TextField(blank=True, null=True)
description = models.TextField(blank=True, null=True)
relation = models.URLField(blank=True, null=True)
subject = models.TextField(blank=True, null=True)
type = models.TextField(blank=True, null=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=True)
language = models.TextField(null=True, blank=True)
contactInformation = models.TextField(null=True, blank=True)
officialInfo = models.BooleanField(default=False)
slug = AutoSlugField(populate_from=['title'], allow_duplicates=True, null=True)
class Meta:
"""Meta class."""
app_label = 'ahmia'
def __unicode__(self):
return unicode(self.about.url)
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(FootballebsiteDescription, self).save(*args, **kwargs)
def __unicode__(self):
return u'%s' % (self.title)
I have a huge amount of links, and i would like to bulk assign them into a category or mark them as blocked based on identical title slug.
Managed to at least get a list of title_slugs with the code below, but the following step, i would like to get an inline list with all sites that have an identical title_slug and bulk assign those all in their a category
class FootballWebsiteInline(admin.TabularInline):
model = FootballWebsite
class FootballWebsiteDescriptionAdmin(admin.ModelAdmin):
list_display = ['show_slug']
def show_slug(self, obj):
return format_html("<a href='{url}'>{url}</a>", url=obj.slug)
inlines = [
FootballWebsiteInline,
]
Above code obviously doesn' t work, since the title slug which can appear many times is not a primary key.
Is it possible to get an inline list based on the title slug in this case which is not a primary key at all, or am i going about this the wrong way?
When possible at all, some further tweaking would be to group the identical title slugs

How to query a django model using another model?

I'm new to django (and python) and I have a question.
I have this model:
class Material(models.Model):
name = models.CharField(max_length=256, blank=True)
description = models.TextField(null=True, blank=True)
def __str__(self):
return self.name
class Meta:
abstract = True
and
class Experiments(models.Model):
title = models.CharField(max_length=200)
experiment = models.TextField(null=True, blank=True)
def __str__(self):
return self.title
I want to query it so I have only have the Materials used in the Experiments model. I was reading about Q objects but I'm not sure how to use it. I appreciate any help!

Accessing a field via a recursive ManyToMany relationship in a Django model

Given the following model:
class Project(models.Model):
project_name = models.CharField(max_length=255)
abstract = models.TextField(blank=True, null=True)
full_description = models.TextField(blank=True, null=True)
date_begun = models.DateField(blank=True, null=True)
related_projects = models.ManyToManyField('self', blank=True, null=True)
class Meta:
ordering = ['project_name']
def __unicode__(self):
return self.project_name
How do I access the ID of projects references in the related_projects field. For example, I can get their project_name values by doing something like this:
def transform_related_projects(self, instance):
return [unicode(rp) for rp in instance.related_projects.all()]
But I can't see how to get the if for the Project record, since the def unicode(self) function only return the project name as a unicode string. I know I'm missing something obvious. Thanks
def transform_related_projects(self, instance):
return [rp.id for rp in instance.related_projects.all()]