uploaded video not showing up - django

So I have uploaded videos for a class model for an educational website but that video is not being rendered. What can I do to render it?
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
My views.py:
class CourseDetailView(LoginRequiredMixin, DetailView):
model = Course
template_name = 'class/course.html'
My html file :
{% extends "class/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<h1>{{ object.title }}</h1>
{{ object.classes.video }}
{% endblock content %}
The output is the title of the class and the <name>.mp4 filename where name is the name of the video file I uploaded. But I want the video to be rendered. Can anyone help me ?
Thanks in advance!

Related

Django form selection box 'jammed' as active so cant make selections

USERS can Upvote or Downvote Posts/Projects posted by Other Users:
screenshot of 'jammed' active dropdown selection box
THIS CODE DIRECTLY BELOW is the models.py that contains the Project class (model) with the vote_total and vote_ratio fields.
It also contains the Review class (model) which is the basis for the ReviewForm in forms.py (code included later)
class Project(models.Model):
owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
featured_image = models.ImageField(null=True, blank=True, default="default.jpg")
demo_link = models.CharField(max_length=2000, null=True, blank=True)
source_link = models.CharField(max_length=2000, 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):
return self.title
class Meta:
# ordering = ['-created']
ordering = ['-vote_ratio', 'vote_total', 'title']
AND here is the Review class (model)
class Review(models.Model):
VOTE_TYPE = (
('up', 'Up Vote'),
('down', 'Down Vote'),
)
owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
project = models.ForeignKey(Project, on_delete=models.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)
class Meta:
unique_together = [['owner', 'project']]
def __str__(self):
return self.value
Here is the ReviewForm from the forms.py
class ReviewForm(ModelForm):
class Meta:
model = Review
fields = ['value', 'body']
labels = {
'value': 'Place your vote',
'body': 'Add a comment with your vote'
}
def __init__(self, *args, **kwargs):
super(ReviewForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs.update({'class': 'input'})
Here is the html template where the form is located
<div class="comments">
<h3 class="singleProject__subtitle">Comments</h3>
<h5 class="project--rating">
{{project.vote_ratio}}% Postitive ({{project.vote_total}} Vote{{project.vote_total|pluralize:"s"}})
</h5>
{% if request.user.profile.id in project.reviewers %}
<p>You have already submitted a comment!</p>
{% elif request.user.profile == project.owner %}
<p>You can't comment your own work!</p>
{% elif request.user.is_authenticated %}
<form class="form" action="{% url 'project' project.id %}" method="POST">
{% csrf_token %}
{% for field in form %}
<div class="form__field">
<label for="formInput#textarea">{{field.label}} </label>
{{field}}
</div>
{% endfor %}
<input class="btn btn--sub btn--lg" type="submit" value="Add Review" />
</form>
{% else %}
Please login to leave a comment
{% endif %}
It was working okay when first implemented and has somehow developed this issue
This is running in venv with Python 3.9.6
Thank you for considering this question !
ADDED - rendered html
rendered html

How to display Data of foreign key in Django html page?

I want to display a Company header and the products below its related company. I am new to django i do not understand this fully.
My models.py
class Company(models.Model):
name = models.CharField(max_length=250)
def __str__(self):
return str(self.name)
class Products(models.Model):
company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="display")
engine = models.CharField(max_length=250, blank=True)
cyl = models.CharField(max_length=250, blank=True)
bore = models.CharField(max_length=250, blank=True)
def __str__(self):
return str(self.engine) + " (ref:" + str(self.ref) + ")"
My views.py:
def Companies(request):
context = {
'categories': Company.objects.all()
}
return render(request, 'product_list.html', context)
My html:
{% for category in categories %}
<h2>{{ category.name }}</h2>
{% for item in category.item_set.all %}
{{ item_engine }}
{% endfor %}
{% endfor %}
only make changes to your HTML file as below and make sure the class name is Product if you are using product_set.all:
{% for category in categories %}
<h2>{{ category.name }}</h2>
{% for item in category.product_set.all %}
{{ item.engine }}
{% endfor %}
{% endfor %}
If still not working then try to remove : + " (ref:" + str(self.ref) + ")"
and also, I think by mistake you have displayed your models.py wrongly. The str functions should be inside the classes like below:
class Company(models.Model):
name = models.CharField(max_length=250)
def __str__(self):
return str(self.name)
class Product(models.Model):
company = models.ForeignKey(Company, on_delete=models.CASCADE,
related_name="display")
engine = models.CharField(max_length=250, blank=True)
cyl = models.CharField(max_length=250, blank=True)
bore = models.CharField(max_length=250, blank=True)
def __str__(self):
return str(self.engine)

List of elements per category within for loop

I have a case, where on my template view I would like to display list of all objects (Issues) and categories (Sprints). I already applied also another filtering to display Issues that belongs to particular Project.
I've managed so far to display Sprints and within each Sprint I am displaying list of issues. How can I apply additional filtering on issues, that only issues belongs to particular sprint will be displayed?
Final result should be to display list of all issues divided per sprint.
My code below:
#views.py
class ProjectBacklogView(DetailView):
model = Project
template_name = 'project-backlog.html'
context_object_name = 'backlog'
def get_context_data(self, **kwargs):
context = super(ProjectBacklogView, self).get_context_data(**kwargs)
context['project'] = Project.objects.all()
context['issue'] = Issue.objects.all().order_by('sprint')
# context['epic'] = Epic.objects.all()
# context['initiative'] = Initiative.objects.all()
context['sprint'] = Sprint.objects.all()
return context
# template.html
{% extends 'base-project.html' %}
{% block content %}
{% for sprint in backlog.sprint_set.all %}
<h4>{{ sprint.name }}</h4>
<div id="simpleList" class="list-group" style="margin-bottom: 2%;">
{% for issue in backlog.issue_set.all %}
<div class="list-group-item">
<div style="float:left;"><strong>{{ issue.title }}</strong></div>
<div style="float: right;"><i class="fas">{{ issue.remaining_estimate }}</i></div>
<br /><br /><hr style="border-top: dashed 1px;"></hr>
<div style="float: left;"><small>Assignee: <strong>{{ issue.assignee }}</strong></small></div>
<div style="float: right;"><small>Initiative: <strong>{{ issue.initiative }}</strong></small></div><br />
<div style="float: left;"><small>Priority: <strong>{{ issue.priority }}</strong></small></div>
<div style="float: right;"><small>Epic: <strong>{{ issue.epic }}</strong></small></div>
</div>
{% endfor %}
<br />
</div>
{% endfor %}
{% endblock %}
#models.py
class Project(models.Model):
PROJECT_TYPE = (
('SCR', 'Scrum'),
('KAN', 'Kanban'),
)
# slug = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
alias = models.CharField(max_length=8, primary_key=True)
name = models.CharField(max_length=160)
project_type = models.CharField(max_length=10, choices=PROJECT_TYPE, default="SCR")
lead = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True)
# Definicja nazwy modelu w Adminie Django
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('project-detail', args=[str(self.alias)])
class Sprint(models.Model):
# sprint_type = models.TextField(default='Sprint', editable=False)
name = models.CharField(max_length=32)
goal = models.TextField(null=True, blank=True)
start_date = models.DateField()
end_date = models.DateField()
project = models.ForeignKey(Project, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Issue(models.Model):
ISSUE_PRIORITY = (
('Critical', 'C'),
('High', 'H'),
('Medium', 'M'),
('Low', 'L'),
)
issue_type = models.TextField(default='Issue', editable=False)
issue_id = models.AutoField(primary_key=True)
# slug = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
title = models.CharField(max_length=128)
description = models.TextField(null=True, blank=True)
initiative = models.ForeignKey(Initiative, on_delete=models.CASCADE, null=True, blank=True)
epic = models.ForeignKey(Epic, null=True, blank=True, on_delete=models.CASCADE)
sprint = models.ForeignKey(Sprint, on_delete=models.CASCADE, null=True, blank=True)
priority = models.CharField(max_length=8, choices=ISSUE_PRIORITY, default='Medium')
assignee = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='assignees', null=True, blank=True) # zczytywane z tabeli userów
author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='authors') # zczytywane z tabeli userów
remaining_estimate = models.IntegerField(null=True, blank=True, default='0') # w minutach
time_logged = models.IntegerField(default='0') # w minutach
attachment = models.FileField(null=True, blank=True) # To Do - multiple files??
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('issue-detail', args=[str(self.issue_id)])
My issue is I don't know how to apply dynamically filter (based on field sprint) as sprints are listed in for loop

Django display related count

i currently try to display who many posts a category has.
Therefor i created the Post Model and the Category Model (See below):
models.py
# Categorys of Post Model
class Category(models.Model):
title = models.CharField(max_length=255, verbose_name="Title")
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
ordering = ['title']
def __str__(self):
return self.title
#Post Model
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField(max_length=10000)
category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
tag = models.CharField(max_length=50, blank=True)
postattachment = fields.FileField(upload_to='postattachment/%Y/%m/%d/', blank=True, null=True)
postcover = fields.ImageField(upload_to='postcover/%Y/%m/%d/', blank=True, null=True, dependencies=[
FileDependency(processor=ImageProcessor(
format='JPEG', scale={'max_width': 300, 'max_height': 300}))
])
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
category_list.html
{% extends 'quickblog/base.html' %}
{% block content %}
{% for categories in categories %}
<div>
<h1><u>{{ categories.title }} {{ $NumCountGetHere }}</u></h1>
</div>
{% endfor %}
{% endblock %}
Now i have no idea how to get the related objects counted...?
You can use something like this:
{% for cat in categories %}
<div>
<h1><u>{{ cat.title }} {{ cat.post_set.count }}</u></h1>
</div>
{% endfor %}
The model Post has a Foreignkey field to the model Category. You can access the related Post instances from a given Category instance using the manager category_instance.post_set. Read about it in the docs.
Finally, we use the method .count() on this manager to get the number of related posts for that given category. This way the code ends up looking like {{ cat.post_set.count }}.

Django {% regroup %} produces duplicate groups

I've defined the following models:
class Topic(models.Model):
class Meta:
ordering = [
'title']
objects = models.Manager()
highlighted = HighlightedTopicManager()
highlight = models.BooleanField(
default=False,
help_text='Show this topic on the home page?',
db_index=True)
highlight_order = models.PositiveSmallIntegerField(
default=0,
help_text='In what order do you want this to be added on the home page?'\
' Leave blank for alphabetic order.',
db_index=True)
title = models.CharField(
max_length=2048,
db_index=True)
slug = models.SlugField(
max_length=128,
db_index=True)
excerpt = models.TextField(
null=True,
blank=True)
description = models.TextField()
def _get_content(self):
if self.excerpt:
return self.excerpt
return self.description
content = property(_get_content)
#models.permalink
def get_absolute_url(self):
return ('academic_projects_topic_detail', (), {'slug': self.slug})
def __unicode__(self):
return self.title
class Project(models.Model):
class Meta:
ordering = [
'topic',
'modified',
'created']
objects = models.Manager()
highlighted = HighlightedProjectManager()
highlight = models.BooleanField(
help_text='Highlight this in the projects\' main page?'\
' Only the most recently modified one will be displayed.')
redirect_to = models.URLField(
blank=True,
null=True,
help_text='Use this for old or extenal projects.')
short_title = models.CharField(
max_length=1024,
db_index=True)
slug = models.SlugField(
max_length=128,
db_index=True)
title = models.CharField(
max_length=2048,
db_index=True)
created = models.DateTimeField(
auto_now_add=True)
modified = models.DateTimeField(
auto_now=True)
excerpt = models.CharField(
max_length=1024,
null=True,
blank=True,
help_text='Concise description to show in the listing page.')
description = models.TextField(
null=True,
blank=True,
help_text='This content will be rendered right after the title.')
downloads = models.ManyToManyField(
Download,
null=True,
blank=True,
help_text='Downloadable files')
footer = models.TextField(
null=True,
blank=True,
help_text='This content will be rendered at the bottom of the page.')
people = models.ManyToManyField(
Person,
help_text='People involved in this project.',
related_name='projects')
organizations = models.ManyToManyField(
Organization,
help_text='Organizations involved other than the lab.',
blank=True,
null=True,
related_name='projects')
publications = models.ManyToManyField(
Publication,
blank=True,
null=True)
topic = models.ForeignKey(
Topic,
verbose_name=_('Main topic'),
help_text='This is the main topic.',
related_name='projects')
sponsors = models.ManyToManyField(
Sponsor,
blank=True,
null=True,
help_text='sponsored_projects')
related_topics = models.ManyToManyField(
Topic,
null=True,
blank=True,
help_text='Optional related topics.',
related_name='secondary_projects')
def __unicode__(self):
return self.short_title
#models.permalink
def get_absolute_url(self):
return ('academic_projects_project_detail', (), {'slug': self.slug})
And use the following template to produce this page (http://seclab.cs.ucsb.edu/academic/projects/):
{% extends "academic/project_base.html" %}
{% block content_title %}Projects{% endblock %}
{% block title %}Projects - {{block.super}}{% endblock %}
{% block content %}
{% regroup object_list|dictsort:"topic" by topic as topic_list %}
{% for topic in topic_list %}
<h2 id="{{ topic.grouper.slug }}">{{ topic.grouper }} #</h2>
{% for project in topic.list %}
<h3>{{ project }}</h3>
<p>{{ project.title }}</p>
{% endfor %}
{% endfor %}
{% endblock %}
The view behind this is a generic one, and invoked as:
url(r'^$',
cache_page(ListView.as_view(
queryset=Project.objects.order_by('topic'),
template_name='academic/project_list.html')),
name='academic_projects_project_list'),
So, Projects are already sorted by Topic. Unfortunately, this code yields to duplicate gorups and, sometimes, the groups change at each refresh (or, at least, they change when I reboot the server).
Any idea of why is this happening? The entire code, besides templates', resides here: https://bitbucket.org/phretor/django-academic/src/
The dictsort filter is only for lists of dicts, you don't need it at all here. Your template should read
{% regroup object_list by topic as topic_list %}