I am trying to create a music streaming website.I have created a base template and extended it to two other templates.One is song_list.html and musicplayer.html.
I have coded the views and urls to get absolute url.
my song_list.html:
{% extends "home.html" %}
{% block content %}
<div class="container">
{% for post in posts %}
{{post.song_title}} by {{post.artist}} from {{post.album}}<br>
{% endfor %}
</div>
<div class="container">
{% include "pagination.html" with page=page_obj %}
</div>
{% endblock %}
I want to render songs from the database in the musicplayer page after clicking the anchor tag.
my msicplayer.html:
{% extends "home.html" %}
{% load i18n %}
{% block content %}
<div class="container">
<form class="" action="mediaplayer.html" method="get">
<div class="data-content">
<div class="container">
<div id="img-1" class="tabcontent">
<div class="blog-content">
<div class="row">
<div class="col-sm">
<div class="card" style="width: 18rem;">
<div class="img">
<img class="img-thumbnail" src="{{ post.img.url }}" alt="">
</div>
<div class="card-body">
<div class="title">
<p>{% trans 'Artist:' %} {{post.artist}} </p><br>
<p>{% trans 'Title:' %} {{post.song_title}}</p><br>
<p>{% trans 'Album:' %} {{post.album}}</p><br>
<p>{% trans 'Duration' %} {{post.song_duration}}</p><br>
</div>
<audio controls>
<source src='{{ post.song.url }}' type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
My app views:
from django.shortcuts import render,get_object_or_404
from .models import song_thumb
from django.core.paginator import Paginator, EmptyPage,PageNotAnInteger
from django.views.generic import ListView
# Create your views here.
class SongListView(ListView):
model=song_thumb
context_object_name='posts'
paginate_by=20
template_name='songlist.html'
def song_detail(request, year, month, day, post):
post=song_thumb.objects.all()
return render(request,'musicplayer.html',{'post': post})
my app models:
from django.db import models
from django.utils import timezone
from django.urls import reverse
# Create your models here.
class song_thumb(models.Model):
artist=models.CharField(max_length=100,null=True)
uploaded_by=models.CharField(max_length=100,null=True)
song_title=models.CharField(max_length=100,null=True)
slug=models.SlugField(max_length=250,null=True)
album=models.CharField(max_length=100,null=True)
song_duration=models.FloatField(null=True)
img=models.ImageField(upload_to='pics',null=True)
song=models.FileField(upload_to='media',null=True)
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
def get_absolute_url(self):
return reverse('song_detail',args=[self.publish.year,
self.publish.month,
self.publish.day, self.slug])
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.song_title
my app urls:
urlpatterns = [
path('',views.SongListView.as_view(),name='songs'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.song_detail,
name='song_detail'),
Like i said,I want a new page with the songdetails and mediaplayer to be rendered after i click the anchor tag in songlist.html.But when I click it i get a blank page.
here, you need to get the post as per the id but you are rendering everything here in you detail. So you can do this
view.py
from django.shortcuts import get_object_or_404
def song_detail(request, post_id):
post=get_object_or_404(Course, pk=post_id)
return render(request,'musicplayer.html',{'post': post})
urls.py
path('<int:post_id>/',views.song_detail,
name='song_detail'),
in you acnhor tag you can link to the particular post
<a href="{% url 'song_detail' post.id %}">
Related
I am building a django blog website and I am trying to upload an image on the website. I can access the photos on the admin page but whenever I try to access it on the page I get an enroll. The trace back says
"
The 'image' attribute has no file associated with it.
This my code for the model
class article(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField()
image = models.ImageField(null=True, blank=True, upload_to='static/media/article')
date = models.DateTimeField(default=timezone.now)
def __str__ (self):
return self.title
def get_absolute_url(self):
return reverse('article-detail', kwargs= {'pk':self.pk})
This is my views code
class ArticleCreateView(LoginRequiredMixin, CreateView):
model = article
fields= ['title', 'content', 'image']
def ArticleCreateView(request):
if request.method == "POST":
form = ArticleForm(request.POST, request.FILES)
if form.is_valid():
article = form.save(commit=False)
article.author = request.user.id
article.save()
return HttpResponse
this is the blog template code
{% extends "agri_tourism/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<section class="flex-container">
<div>
{% for article in articles %}
<article class="media content-section">
{% load static %}
<div class="media-body">
<div style="text-decoration:none; display: inline-block;" class="article-metadata">
<img class="rounded-circle article-img" src="{{user.profile.image.url}}">
<a style="text-decoration:none;" class="mr-2" href="#">{{ article.author }}</a>
<small class="article-date">{{ article.date|date:"F d, Y" }}</small>
</div>
<h2><a class="article-title" href="">{{ article.title }}</a></h2>
<p class="article-content">{{ article.content }}</p>
<img class="image-content" id="image-el" src = "{{article.image.url}}">
<div class="like-share-btns">
</div>
</article>
{% endfor %}
The form page code is below
{% extends "agri_tourism/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class = "content-section">
<div class = "container">
<div class = "row md-8">
<form method = "POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class = "form-group">
<legend class ="border-bottom mb-4">Blog article</legend>
{{form|crispy }}
{{form.media}}
</fieldset>
<div class= "form-group">
<button class="btn btn-outline-info" type="submit" style= "margin-top:4px; ">Submit the Article</button>
</div>
</form>
</div>
</div>
</div>
I want to access photos on the blog page
check the image with if condition like this...
<div class="media-body">
<div style="text-decoration:none; display: inline-block;" class="article-metadata">
{% if user.profile.image.url %}
<img class="rounded-circle article-img" src="{{user.profile.image.url}}">
{% endif %}
<a style="text-decoration:none;" class="mr-2" href="#">{{ article.author }}</a>
<small class="article-date">{{ article.date|date:"F d, Y" }}</small>
</div>
and also check those settings
urls.py (in project directory)
from django.conf import settings # --------> this
from django.conf.urls.static import static # --------> this
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # --------> this
settings.py (in project directory)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
I tried several ways to upload images to a specific destination. Showing no error but the image is not uploading to the destination.
views.py
from django.views.generic.edit import CreateView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
fields = ['name', 'weblink', 'image']
success_url = reverse_lazy('posts')
template_name = 'base/post.html'
def form_valid(self, form):
# form.instance.post_id = self.kwargs['pk']
form.instance.author = self.request.user
return super().form_valid(form)
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
name = models.CharField(max_length=200)
weblink = models.CharField(max_length=200)
image = models.ImageField(default='default.png', upload_to='uploads/%Y/%m/%d/')
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return f'Added {self.name} Profile'
urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
.....
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
template
{% extends 'base/base.html' %}
{% block content %}
<div class="row justify-content-md-center home">
<div class="col-md-6 create-form">
← Back
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-md-6 submit-form">
<form action="" method="POST">
{% csrf_token %}
{{form.as_p}}
<button class="btn btn-info" type="submit">Submit</button>
</form>
</div>
</div>
{% endblock content %}
I added also the media root and URL in the settings file. I didn't any clue but unable to upload the file to the specific location.
When your form is supposed to submit files you must set the enctype attribute on the form tag to multipart/form-data otherwise files won't be submitted:
{% extends 'base/base.html' %}
{% block content %}
<div class="row justify-content-md-center home">
<div class="col-md-6 create-form">
← Back
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-md-6 submit-form">
<!-- Set it here ↓ -->
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<button class="btn btn-info" type="submit">Submit</button>
</form>
</div>
</div>
{% endblock content %}
I have been working on to make the website which people can post their review on restaurants. I finished creating urls.py, views.py, models.py and html file.
I tried to connect the list page with the detailed page on each restaurants. Therefore, I used str:pk tag to connect list page with detail page.
However it does't work and however times I check, I can't find why the error happens.
settings and other settings are already done. I only have to adjust app files.
My Goal:
List of restaurants are already created. I want user to be able to go to the detail page by clicking the button below the "{{ list.outline}}"
models.py
from django.db import models
from django.utils import timezone
stars = [
(1,"☆"),
(2,"☆☆"),
(3,"☆☆☆"),
(4,"☆☆☆☆"),
(5,"☆☆☆☆☆")
]
# Create your models here.
class Tabelog(models.Model):
store_name = models.CharField("店名",max_length = 124,primary_key=True)
title = models.CharField("タイトル",max_length = 124,null=True,blank=True)
evaluation = models.IntegerField("評価",choices = stars)
comment = models.TextField("口コミ")
create_date = models.DateField("口コミ投稿日",default=timezone.now)
price = models.PositiveIntegerField("値段",help_text='円',default=0)
def outline(self):
return self.comment[:10]
def __str__(self):
return ("{},{},{}".format(self.store_name,self.evaluation,self.comment[:10]))
urls.py
from django.urls import path,include
from Tabelog import views
from Tabelog.views import ReviewList,ReviewDetail,ReviewForm,ReviewFix,ReviewDelete,ReviewContact,ReviewContactComplete
app_name = "Tabelog"
urlpatterns = [
path("lp/", views.lp,name="lp"),
path("list/", ReviewList.as_view(),name="list"),
path("detail/<str:pk>/",ReviewDetail.as_view(),name="detail"),
path("form/",ReviewForm.as_view(),name="form"),
path("form/fix/<str:pk>/",ReviewFix.as_view(),name="form_fix"),
path("form/delete/<str:pk>/",ReviewDelete.as_view(),name="delete"),
path("contact/",ReviewContact.as_view(),name="contact"),
path("contact/complete/",ReviewContactComplete.as_view(),name="ContactComplete")
]
forms.py
from django.shortcuts import render,redirect,get_object_or_404
from Tabelog.models import Tabelog
from Tabelog.forms import CreateTabelogForm
from django.views import generic
from Tabelog.forms import CreateTabelogForm,ContactForm
from django.urls import reverse_lazy
from django.core.mail import send_mail
from django.template.loader import render_to_string
# Create your views here.
def lp(request):
return render(request,"Tabelog/lp.html")
class ReviewList(generic.ListView):
model = Tabelog
class ReviewDetail(generic.DetailView):
model = Tabelog
class ReviewForm(generic.CreateView):
model = Tabelog
form_class = CreateTabelogForm
success_url = reverse_lazy("Tabelog:list")
class ReviewFix(generic.UpdateView):
model = Tabelog
fields = "__all__"
success_url = reverse_lazy("Tabelog:list")
class ReviewDelete(generic.DeleteView):
model = Tabelog
success_url = reverse_lazy("Tabelog:list")
class ReviewContact(generic.FormView):
template_name = "Tabelog/tabelog_contact.html"
form_class = ContactForm
success_url = reverse_lazy("Tabelog:ContactComplete")
def form_valid(self,form):
subject = "お問い合わせがありました"
message = render_to_string('Tabelog/mail.txt',form.cleaned_data,self.request)
from_email = "toiawase#gmail.com"
recipient_list = ["yutotennisnowboard#gmail.com"]
send_mail(subject,message,from_email,recipient_list)
return redirect('Tabelog:list')
class ReviewContactComplete(generic.TemplateView):
template_name = "Tabelog/tabelog_contact_complete.html"
tabelog_list.html
<!DOCTYPE html>
{% extends 'diary/base.html' %}
{% block title %}お店リスト{% endblock %}
{% block content %}
{% for list in object_list %}
<div class="card border-primary mb-3">
<div class="card-body text-primary">
<h1 class="card-title">{{list.store_name}}</h1>
<h2 class="card-text">{{ list.get_evaluation_display}}</h2>
<span class="card-text">{{ list.outline}}</span><br>
<button type="button" class="btn btn-light"> See More Detail! </button>
</div>
</div>
{% endfor %}
{% endblock %}
tabelog_detail.html
<!DOCTYPE html>
{% extends 'diary/base.html' %}
{% load static %}
{% block title %}Detail Page{% endblock %}
{% block design %}
<link rel="stylesheet" href="{% static 'css/detail.css' %}">
{% endblock %}
{% block content %}
<div class="container">
<div class="card border-info mb-3">
<div class="card-body">
<h1 class="card-title">{{object.title}}</h1>
<p class="card-text">投稿者:{{ object.writer }}</p>
<p class="card-text">作成日:{{ object.created_at}}</p>
<p class="card-text">更新日:{{ object.last_modefied}}</p>
<p class="card-text">カテゴリ:{{ object.category}}</p>
<p class="card-text">タグ:{% for tag in object.tag.all %}{{tag}},{% endfor %}</p>
<div class="card-text">
{{object.text| linebreaks | urlize }}
</div><br>
<button type="button" class="btn btn-light"> Change the post </button>
</div>
</div>
</div>
<div class="container">
<button type="button" class="btn btn-light"> コメントする</button>
</div>
<div class="container">
<article class="card border-info mb-3" id="comment">
<div class="card-body">
{% for comment in article.comment_set.all %}
<p class="card-text">{{comment | linebreaks | urlize}}</p>
{% endfor %}
</div>
</article>
</div>
{% endblock %}
The problem was caused by the detail page connected from list page. I realized that the error message doesn't necessarily show the specific cause.
I'm trying to make a simple portofolio app using django but I'm keep getting this error.
I looked everywhere on google but nothing helps.
I'm basically trying to link the Read more button(in project_index.html) to the project_details.html page using {% url 'project_detail' pk=project.pk %}
Views.py:
from django.shortcuts import render
from projects.models import Project
# Create your views here.
def project_index(request):
projects = Project.objects.all()
context = {"projects": projects}
return render(request, "project_index.html", context)
def project_detail(request, pk):
project = Project.objects.get(pk=pk)
context = {"project": project}
return render(request, "project_detail.html", context)
Urls.py:
from django.urls import path
from projects import views
urlpatterns = [
path("", views.project_index, name="project_index"),
path("/int:pk/", views.project_detail, name="project_detail"),
]
models.py:
from django.db import models
# Create your models here.
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
technology = models.CharField(max_length=20)
image = models.FilePathField(path="/img")
project_index.html:
{% extends "base.html" %}
{% load static %}
{% block page_content %}
<h1>Projects</h1>
<div class="row">
{% for project in projects %}
<div class="col-md-4">
<div class="card mb-2">
<img class="card-img-top" src="{% static project.image %}">
<div class="card-body">
<h5 class="card-title">{{ project.title }}</h5>
<p class="card-text">{{ project.description }}</p>
**<a href="{% url 'project_detail' pk=project.pk %}"**
class="btn btn-primary">Read More</a>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
project_detail.html:
{% extends "base.html" %}
{% load static %}
{% block page_content %}
<h1>{{ project.title }}</h1>
<div class="row">
<div class="col-md-8">
<img src="{% static project.image %}" alt="" width="100%">
</div>
<div class="col-md-4">
<h5>About the project:</h5>
<p>{{ project.description }}</p>
<br>
<h5>Technology used:</h5>
<p>{{ project.technology }}</p>
</div>
</div>
{% endblock %}
Thanks in advance.
correct your url
path("<int:pk>/", views.project_detail, name="project_detail")
I want to iterate over my postlist, to show on click all the posts with the same tag.
I want them to display at the index.html .
I understand the function, but i don´t know how to implement it into my template.
My views.py
from django.views import generic
from .models import Post
from django.shortcuts import render
class PostList(generic.ListView):
model = Post
template_name = 'index.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'
def tag(request, slug):
posts = Post.objects.filter(tags__slug=tag)
return render(request, 'index.html', {"post_list": posts, "tag": tag})
def about(request):
return render(request, 'about.html', {})
My template
<header class="masthead" >
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="site-heading">
<h5 class=" site-heading mt-3"> Erfolgreiche Problemlösungen in der Programmierung, Linux und Windows</h5>
<p class="texthead">
</p>
</div>
</div>
</div>
</div>
</div>
</header>
<div class="container">
<div class="row">
<!-- Blog Entries Column -->
<div class="col-md-8 mt-3 left">
{% for post in post_list %}
<div class="card mb-4" >
<div class="card-body">
<h2 class="card-title">{{ post.title }}</h2>
<p class="card-text text-muted h6">{{ post.author }} | {{ post.created_on | date:"d M Y"}} | Tag:
{% for tag in post.tags.all %}
<a class="mycardtext" href="{% url 'tag' tag.slug %}">{{ tag.name }}</a>
{% empty %}
None
{% endfor %}
</p>
<p class="card-text">{{post.content|truncatewords:25|safe}}</p>
<div><a href="{% url 'post_detail' post.slug %}"
class="btn btn-danger">Weiterlesen</a></h3>
</div>
</div>
</div>
{% endfor %}
</div>
{% block sidebar %}
{% include 'sidebar.html' %}
{% endblock sidebar %}
</div>
</div>
{%endblock%}
My Urls.py
from . import views
from django.urls import path
from django.urls import include
from django.views.generic.base import RedirectView
favicon_view = RedirectView.as_view(url='/home/UrosDobricic/mysite/static/favicon.png', permanent=True)
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('about', views.about, name='about'),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
path("tag/<slug:slug>/", views.tag, name='tag'),
]
The tags are shown on the blog. My problem is, that i created in the views.py this post_list = Post.objects.filter(tags__slug=tag), but in my template i have no posts definded.
So when i define the part :{% for tag in post.tags.all %} into to {% for tag in post_list.tags.all %}, it shows me "NONE" at my blog.
I can´t get the right solution, so i wanted to ask if somebody has a tip for me.
Generally this means that i have to display
{% for tags in post_list %}
{{ tags }}
{% endfor %}
Or am I wrong?
If somebody can answer with an example based on my files, that would be great.