calling a class inside another class function - django

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

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!

Should I use Many-to-one relationship or a Many-to-many?

Basically I am creating a website using django where I have created a class called courses and a separate class Class. I'm now confused which relationship I should use.
My code:
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.name
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
Thanks in advance!
Change your code to
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)
enrolled_students = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='enrolled_students', blank=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
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img = Image.open(self.image.path)
if img.height > 285 or img.width > 201:
output_size = (285, 201)
img.thumbnail(output_size)
img.save(self.image.path)
img2 = Image.open(self.instructor_image.path)
if img2.height > 40 or img2.width > 40:
output_size = (40, 40)
img2.thumbnail(output_size)
img2.save(self.instructor_image.path)
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
Thinking about your problem, each Class can only belong to one course, but each course can have multiple classes correct?
If that's the case then you should have a many to one where many is the class and the course is the one.
You already have it somewhat in your code
students = models.ManyToManyField(User, related_name='courses_joined', blank=True)
classes = models.OneToManyField(Class, related_name='...')
I reckon that the course will be divided into classes. So, the Class model will contain a ForeignKey field that points to the Course model.
More precisely, this is what OP will want
class Class(models.Model):
course = models.ForeignKey(Course, related_name='classes', on_delete=models.CASCADE)

Is there a way to update top level relationship in Django form?

I have below models and form.
Brand > Section > Category > Article.
I can pull the existing data out of the database however I have hit a wall. I am trying to create a new article or update an existing article but I'm not sure how I can update the brand, then the Section. The Category I can update and it is connected directly to the Article model. I have been thinking about this for a few days now and tried different models but ultimately i can't think of the best way to connect the models and have them update in the model.
class Brand(models.Model):
def brand_image(instance, filename):
return 'uploads/brand/{0}/{1}'.format(instance.title, filename)
title = models.CharField(max_length=50, unique=True, blank=True, null=True)
image = models.ImageField(upload_to=brand_image, null=True, blank=True)
slug = AutoSlugField(populate_from='title', unique_with='title', blank=True, null=True)
my_order = models.PositiveIntegerField(default=0, blank=False, null=False)
class Meta:
ordering = ['my_order']
def __str__(self):
return self.title or ''
def get_absolute_url(self):
return reverse('brand-list', kwargs={'brand_slug': self.slug})
class Section(models.Model):
title = models.CharField(max_length=50,unique=True, blank=True,null=True)
slug = AutoSlugField(populate_from='title', unique_with='title',blank=True,null=True)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name='section', blank=False, null=False)
my_order = models.PositiveIntegerField(default=0, blank=False, null=False)
class Meta:
ordering = ['my_order']
def __str__(self):
return self.title or ''
def get_absolute_url(self):
return reverse('section-list', kwargs={'section_slug': self.slug})
class Category(models.Model):
title = models.CharField(max_length=50, blank=True,null=True)
slug = AutoSlugField(populate_from='title', unique_with='title',blank=True,null=True)
my_order = models.PositiveIntegerField(default=0, blank=False, null=False)
section = models.ForeignKey(Section, on_delete=models.CASCADE,related_name='category', blank=False ,null=False)
class Meta:
ordering = ['my_order']
def __str__(self):
return self.title or ''
def get_absolute_url(self):
return reverse('category-list', kwargs={'category_slug': self.slug})
class Article(models.Model):
title = models.CharField(max_length=100, unique=True, db_index=True)
description = models.CharField(max_length=100, blank=True, null=False)
category = models.ForeignKey(Category, on_delete=PROTECT, related_name='article', null=False, default=1)
slug = AutoSlugField(populate_from='title', unique_with='created__month')
content = HTMLField(null=True,blank=True)
internal = models.BooleanField(default=False)
status = models.CharField(max_length=30, choices=STATUS_CHOICES, default='Draft')
author = models.ForeignKey(User, related_name='author' ,on_delete=PROTECT,null=True)
updated_by = models.ForeignKey(User, related_name='updated_by',on_delete=PROTECT,null=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
video = models.FileField(blank=True, null=True, upload_to='articles/videos')
favourites = models.ManyToManyField(User, related_name='art_favourite', default=None, blank=True)
tags = TaggableManager(related_name='tags', help_text='Comma or space separated list', blank=True)
pinned = models.BooleanField(default=False)
def __str__(self) -> str:
return self.title
def get_absolute_url(self):
return reverse('articles-detail', kwargs={'article_slug': self.slug})
class ArticleForm(forms.ModelForm):
title = forms.CharField(label='Article Title', max_length=100,)
description = forms.CharField(label='Description', max_length=100,required=False)
content = forms.CharField(label='Article Content',widget=CKEditorUploadingWidget(attrs={'cols': 80, 'rows': 30}))
video = forms.FileField(help_text="Valid file Extension - .mp4", required=False, validators=[validate_file_extension])
category = GroupedModelChoiceField(queryset=Category.objects.exclude(section=None).order_by('section'),choices_groupby='section')
internal = forms.BooleanField(required=False, help_text='Is this for internal use only?', label='Internal Article')
class Meta:
model = Article
exclude = ['slug','author','created','updated','updated_by','favourites','votes','views','section']
widgets = {"tags": TagWidget(attrs={"data-role": "tagsinput"})}
Any help or guidance would be greatly appreciated.
Your Article model has a foreign key link to Section for some reason. However your stated heirarchy and models use the following one-to-many relations, which creates a direct link up the chain.
Brand < Section < Category < Article.
This means that by choosing the Category you could also choose Brand and Section. If your Article had a foreign key link to Category instead, then all the information above about groups above Article could be obtained via the article, eg, article.category__section__brand. Changing the category would, by default, update section and brand. You could do this in a single dropdown that contained Category.objects.all - perhaps with the dropdown option text also containing brand and section info for clarity and sorting purposes.

Django Model, Multi value / Admin Area

I have start fresh with Django.
I am creating a blog and I need a hint now.
I want to add tags to my posts.
So I created a model for my tags:
class Tag(models.Model):
name = models.CharField(max_length=200, unique=True)
def __str__(self):
return self.name
This is my Post Model
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
What is the best way, that the user can select in the admin area tags for the post and more than one or create a new tag?
In the Post class, add a field ManyToMany
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
updated_on = models.DateTimeField(auto_now= True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
tag = models.ManyToManyField(Tag)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
You are looking for InlineModelAdmin particulary section regarding
Working with many-to-many models
something as following:
class TagInline(admin.TabularInline):
model = Post.tags.through
class PostAdmin(admin.ModelAdmin):
inlines = [
TagInline,
]
Also you are missing relationship on your model which should be ManyToMany
class Post(models.Model):
...
tags = models.ManyToManyField(Tag)

Tricky issue passing data from form to form in django

I am a django newbie and have one more big struggle for longer time... :/
User can choose a 'main language' which is set as ForeignKey. User can choose 'further languages' as ManyToMany (Checkbox). Assuming, user selects english as 'main' language, so english has to be filterd out from the 'further languages'... have been searching so much and have no idea how to do it. Is this even possible without JavaScript?
Of course, I could set the 'queryset' in the second form but it would filter the objects after the submit... The similar problem is, when a selected country has to be connected to the proper zipcodes...
I am very thankful for any hints.
Best regards.
class Country(models.Model):
enter code here
country = models.CharField(max_length=40)
active = models.BooleanField(default=True)
class Meta:
verbose_name_plural = 'Länder'
def __str__(self):
return self.country
class ZipCode(models.Model):
zipcode = models.CharField(max_length=5)
city = models.CharField(max_length=255)
active = models.BooleanField(default=False)
class Meta:
verbose_name_plural = 'Postleitzahlen'
def __str__(self):
return '{0} {1}'.format(self.zipcode, self.city)
class MainLanguage(models.Model):
language = models.CharField(verbose_name='Hauptsprache', max_length=40)
active = models.BooleanField(default=True)
class Meta:
verbose_name_plural = 'Hauptsprachen'
ordering = ['language']
def __str__(self):
return self.language
class SecondLanguage(models.Model):
language = models.CharField(verbose_name='weitere Sprachen', max_length=40)
active = models.BooleanField(default=False)
class Meta:
verbose_name_plural = 'weitere Sprachen'
ordering = ['language']
def __str__(self):
return self.language
class CustomUserprofile(models.Model):
user = models.OneToOneField(User)
name = models.CharField(verbose_name='Vorname', max_length=40,
null=True, blank=True)
country = models.ForeignKey(Country, verbose_name='Land',
null=True, blank=True)
zipcode = models.ForeignKey(ZipCode, blank=True, null=True)
main_language = models.ForeignKey(
MainLanguage, verbose_name='Hauptsprache',
null=True, blank=True)
second_language = models.ManyToManyField(
SecondLanguage, verbose_name='weitere Sprachen',
null=True, blank=True)
class UserProfileForm(forms.ModelForm):
second_language = forms.ModelMultipleChoiceField(
queryset=SecondLanguage.objects.all(),
required=False,
widget=forms.CheckboxSelectMultiple)
class Meta:
model = CustomUserprofile
exclude = ('user',)