The site is able to display the whole content of the blog but not the video contents. When I try to post a new post including video. It's just show html script. Is there anyway to pass the whole html from python?
I'm using post.content to pass the post content to the html page. It works with text, but not image or video.
home.html:
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{{ url_for('users.user_posts', username=post.author.username)}}">{{ post.author.username }}</a>
<small class="text-muted">{{ post.date_posted.strftime('%Y-%m-%d') }}</small>
</div>
<h2><a class="article-title" href="{{ url_for('posts.post',post_id=post.id) }}">{{ post.title }}</a></h2>
<div class="article-content"><{{ post.content }}></div>
</div>
Routes.py
def home():
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(Post.date_posted.desc()) \
.paginate(page=page, per_page=5)
return render_template('home.html', posts=posts)
sample image
I just found the answer. Just use this:
{{ post.content|safe }}
Work like a charm.
Refer: passing string with html tags to html from python
Related
I want to save the url of images in my database using django shell
here is my model
class Album(models.Model):
reference = models.IntegerField(null = True)
created_at = models.DateTimeField(auto_now_add=True)
available = models.BooleanField(default=True)
title = models.CharField(max_length=200)
picture = models.URLField()
artists = models.ManyToManyField(Artist, related_name='albums', blank=True)
here is what i did in the shell
album = Album.objects.create(title="Funambule", picture="/home/etali/Images/moi.png")
the url is correctly save in the database but it's impossible to load it in the view
here is the view
<div class="col-sm-4 text-center">
<a href="/">
<img class="img-responsive" src="{{ album.picture }}" alt="{{ album.title }}">
</a>
<h3>{{ album.title }}</h3>
{% for artist in album.artists.all %}
<p>{{ artist.name }}</p>
{% endfor %}
</div>
here is the error that appears when I inspect the code
I am creating E-Learning website and I want to show "Course Content or Lession" as a playlist which is related to subject. Like that image
but I am getting error Cannot query "Python Tutorials Teaser": Must be "Subject" instance. Python Tutorials Teaser is title of the lession.
view.py
def allsubject(request):
subj = Subject.objects.all()
context = {'subj': subj}
return render(request, 'allsubject.html', context)
def pvideos(request, slug):
vds = Videos.objects.filter(slug=slug).first()
coursecontent = Videos.objects.filter(subject=vds)
context = {'vds':vds, 'coursecontent':coursecontent}
return render(request, 'pvideos.html', context)
models.py
class Videos(models.Model):
sno = models.AutoField(primary_key=True)
title = models.CharField(max_length=500)
cont = models.TextField()
vurl = models.URLField(max_length=200)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='videos')
position = models.PositiveSmallIntegerField(verbose_name="videono.")
slug = models.CharField(max_length=130)
timeStamp = models.DateTimeField(default=now)
def __str__(self):
return self.title
pvideo.html
{% extends 'base.html' %}
{% block title %}Free Video Course {% endblock title %}
{% block body %}
<div class="container">
<div class="embed-responsive embed-responsive-21by9">
<iframe class="embed-responsive-item" src="{{vds.vurl}}" allowfullscreen></iframe>
</div>
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active font-weight-bold" id="home-tab" data-toggle="tab" href="#overview" role="tab"
aria-controls="home" aria-selected="true">Overview</a>
</li>
<li class="nav-item">
<a class="nav-link font-weight-bold" id="profile-tab" data-toggle="tab" href="#coursecontent" role="tab"
aria-controls="profile" aria-selected="false">Course Content</a>
</li>
</ul>
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="overview" role="tabpanel" aria-labelledby="home-tab">
<h2>{{vds.title}}</h2>
<p>{{vds.cont|safe}}</p>
</div>
<div class="tab-pane fade" id="coursecontent" role="tabpanel" aria-labelledby="profile-tab">
{% for c in coursecontent %}
{{c.title}}
{% endfor %}
</div>
</div>
</div>
{% endblock body %}
I think I made a mistake on views.py coursecontent = Videos.objects.filter(subject=vds). I want to show this playlist on that page where I show lessions. I hope you understand what I want. If anyone has any other idea besides this, so please help me.
I user click on course content then I show all lession related to subject
You are right, you have made a mistake in coursecontent = Videos.objects.filter(subject=vds)
Subject must either be the pk or an instance of subject but you're giving it another video instance. What you want is
coursecontent = Videos.objects.filter(subject=vds.subject).exclude(sno=vds.sno)
.filter(subject=vds.subject) will give you all videos with the same subject.
.exclude(sno=vds.sno) will exclude the current video from the query. This is useful if you want to show only the other videos... If you want to include all, just skip that part.
As a side note, you might want to improve your variable naming.
vds could be called video (it's singular)
vurl could be just url
cont could be content
Most of your model names should be singular (coz each is a single instance).
An e-learning website is a nice initiative.
I want to POST a form from my html to views.py in django, but I am not able do it.
This is my html. This form should post the url of the downloaded image to the views.py function.
{% for x in photo %}
<a class="down" href="{{x.image.url}}" onclick="myfunc()" download="none">get</a>
<form action="/image_info/" method="POST" id='dform'>
{% csrf_token %}
<input name='d_button' type="hidden" value="{{x.image.url}}">
</form>
{% endfor %}
This is my javascript function to submit form whenever the get link is pressed
<script type="text/javascript">
function myfunc()
{
document.getElementById("dform").submit();
console.log('hello');
}
</script>
this is my views.py. This should take the image url from the form and display it in the new page.
def show_image():
image_url = request.POST.get('d_button', None)
return render(request, 'show_image.html', {'image': image_url)
but my problem is that the form is not returning the url of the image that is clicked instead it is returning the url of first link. for example
link1
link2
link3
link4
if I click on link3, it is downloading the image in link3 but POSTING the url of link1.
This is a bit tricky to explain but this is the best I can.
Thanks in advance.
HTML ids are supposed to be unique. You are looping while generating these forms and hence generate a bunch of duplicate ids, so when you write document.getElementById("dform") the first matching element is selected.
One solution would be to use forloop.counter to generate unique ids and use them. We would set these ids as an attribute on the anchor and pass the anchor element to the onclick function:
{% for x in photo %}
<a class="down" href="{{x.image.url}}" onclick="myfunc(this)" data-target="dform-{{ forloop.counter }}" download="none">get</a>
<form action="/image_info/" method="POST" id='dform-{{ forloop.counter }}'>
{% csrf_token %}
<input name='d_button' type="hidden" value="{{x.image.url}}">
</form>
{% endfor %}
Now in your javascript:
<script type="text/javascript">
function myfunc(elem)
{
document.getElementById(elem.getAttribute("data-target")).submit();
console.log('hello');
}
</script>
Help required, please.
I'm doing a level 6 Diploma in Software Development. Right now I'm doing a project that requires a gym app to be built.
We've decided on using Python/Django as our language/framework.
I have my models, urls, views, and templates working thus far. (Videos display and its own page)
However, I need to implement a search bar to search both video content and text context within the app.
I have the video model set up in /admin. migrations are done.
Do I need another model to search for normal content in my app?
The search bar is in my base.html template.
I want to use the search bar to do a query and pass the results onto a results template page
which extends base.html.
The error I get is the below;
Exception Type: ValueError
Exception Value: Cannot use None as a query value
Can someone point me in the right direction? photos of code attached.
base.html
<!-- Navbar Right Side -->
<div class="navbar-nav">
<form class="form-inline my-1 my-lg-0" action="{% url 'search_results' %}" method="get">
<input name="q" type="text" placeholder="Search" aria-label="Search">
<a class="btn btn-secondary my-2 my-sm-0" href='/gymapp/videos/' type=submit>Search</a>
</form>
<a class="nav-item nav-link" href="#">Login</a>
<a class="nav-item nav-link" href="/register">Register</a>
</div>
search_results.html
{% extends "gymapp/base.html" %}
{% load embed_video_tags %}
{% block content %}
{% for i in obj %}
{% video i.video 'tiny' %}
<ul class="list-unstyled mt-3 mb-4">
<li>Name: {{ i.video_name }}</li>
<li>Description: {{ i.content }}</li>
</ul>
{% endfor %}
{% endblock content %}
urls.py
path('videos/', VideoResultsView.as_view(), name='search_results'),
models.py
from django.db import models
from embed_video.fields import EmbedVideoField
class Video(models.Model):
category = models.CharField(max_length=200)
video_name = models.CharField(max_length=200)
content = models.CharField(max_length=500)
video = EmbedVideoField() # same like models.URLField()
stats = models.CharField(max_length=20)
class Meta:
verbose_name_plural = 'videos'
def __str__(self):
return self.category
views.py
class VideoResultsView(ListView):
model = Video
template_name = 'search_results.html'
def get_queryset(self):
query = self.request.GET.get('q')
video_list = Video.objects.filter(
Q(category__icontains=query) | Q(video_name__icontains=query)
)
return video_list
Hoping someone can point me in the right direction. Error Description
Found my answer.
<form class="form-inline my-1 my-lg-0" action="{% url 'search_results' %}" method="get">
<input name="q" type="text" placeholder="Search" aria-label="Search">
<a class="btn btn-secondary my-2 my-sm-0" href='/gymapp/videos/' type=submit>Search</a>
</form>
I shouldn't have used an tag for the button. Changed it to tag and now the query is working.
silly mistake.
I created a Link model in my django project that loads in as navigation links in my base.html file which is the template that is being inherited by the other html files.
I have tried the usual way or at least the way i was taught using Listview,{% for %}
def view_link(ListView):
context_object_name = 'links'
Model = Links
Class Link(Models):
link_name = models.CharField(max_length=265)
<nav class="navbar navbar-expand-lg">
<a class="navbar-brand">HOME</a>
<button class="navbar-toggler" data-toggle="collapse" data-target="#collapseMenu">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar navbar-collapse">
<ul class="navbar-nav">
{% for link in links %}
<li class="nav-item"><a class="nav-link">{{ link.link_name}}</a></li>
{% endfor %}
</ul>
</div>
</nav>
I expect the to query the link_names i stored in my link model to query as links for my navigation bar but instead it returns blank but when i do it manually and add links one by one it shows all of the links
Can you please correct your model name in the view.
Model = Links
it should be Model = Link.
Thanks.