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.
Related
my views.py file:
from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import (
LoginRequiredMixin,
UserPassesTestMixin,
)
from .models import Post
# Create your views here.
class PostListView(ListView):
model = Post
template_name = "blog/index.html"
context_object_name = "posts"
ordering = ["-date_posted"]
class PostDetailView(DetailView):
model = Post
class PostCreateView(CreateView, LoginRequiredMixin, UserPassesTestMixin):
model = Post
fields = ['title', 'genere', 'content']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostUpdateView(UpdateView, LoginRequiredMixin, UserPassesTestMixin):
model = Post
success_url = "blog-home"
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class PostDeleteView(DeleteView, LoginRequiredMixin, UserPassesTestMixin):
model = Post
success_url = "/"
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
def about(request):
return render(request, 'blog/about.html')
My models.py:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
genere = models.CharField(max_length=50, default='')
def __str__(self):
return f'{self.title} by {self.author}'
def get_absolute_url(self):
return reverse('blog-home')
my urls.py url:
from django.urls import path
from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView
from . import views
urlpatterns = [
path("", PostListView.as_view(), name="blog-home"),
path("about", views.about, name="blog-about"),
path("post/<int:pk>", PostDetailView.as_view(), name="blog-detail"),
path("post/new", PostCreateView.as_view(), name="blog-create"),
path("post/<int:pk>/update", PostUpdateView.as_view(), name="blog-update"),
path("post/<int:pk>/delete", PostDeleteView.as_view(), name="blog-delete"),
]
index.html
{% extends "blog/base.html" %}
{% load static %}
{% block content %}
<div class="row tm-row">
{% for post in posts %}
<article class="col-12 col-md-6 tm-post">
<hr class="tm-hr-primary">
<a href="{% url 'blog-detail' post.id %}" class="effect-lily tm-post-link tm-pt-60">
<div class="tm-post-link-inner">
<img src="{% static 'img/img-01.jpg' %}" alt="Image" class="img-fluid">
</div>
<span class="position-absolute tm-new-badge">New</span>
<h2 class="tm-pt-30 tm-color-primary tm-post-title">{{ post.title }}</h2>
</a>
<p class="tm-pt-30">
{{ post.content|safe|truncatewords:"30"|linebreaks }}
</p>
<div class="d-flex justify-content-between tm-pt-45">
<span class="tm-color-primary">{{ post.genere }}</span>
<span class="tm-color-primary">{{ post.date_posted|date:'N j,Y' }}</span>
</div>
<hr>
<div class="d-flex justify-content-between">
<span>36 comments</span>
<span>by {{ post.author }}</span>
</div>
</article>
{% endfor %}
</div>
{% endblock %}
post_detail.html:
{% extends 'blog/base.html' %}
{% load crispy_forms_tags %}
{% load static %}
{% block content %}
<div class="container">
<article class="col-12 col-md-6 tm-post">
<hr class="tm-hr-primary">
<a href="" class="effect-lily tm-post-link tm-pt-60">
<div class="tm-post-link-inner">
<img src="{% static 'img/img-01.jpg' %}" alt="Image" class="img-fluid">
</div>
<span class="position-absolute tm-new-badge">New</span>
<h2 class="tm-pt-30 tm-color-primary tm-post-title">{{ object.title }}</h2>
{% if object.author == user %}
<a class="btn btn-outline-danger" href="{% url 'blog-delete' object.id %}">Delete</a>
<a class="btn btn-outline-secondary" href="{% url 'blog-update' object.id %}">Update</a>
{% endif %}
</a>
<p class="tm-pt-30">
{{ object.content }}
</p>
<div class="d-flex justify-content-between tm-pt-45">
<span class="tm-color-primary">{{ object.genere }}</span>
<span class="tm-color-primary">{{ object.date_posted|date:'N j,Y' }}</span>
</div>
<hr>
<div class="d-flex justify-content-between">
<span>36 comments</span>
<span>by {{ object.author }}</span>
</div>
</article>
</div>
{% endblock %}
post_confirm_delete.html:
{% extends 'blog/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
<form method="POST">
{% csrf_token %}
<h2>Are You Sure You Want To Delete "{{ object.title }}"</h2>
<button class="btn btn-outline-danger">Yes, I'm Sure</button>
<a class="btn btn-outline-secondary" href="{% url 'blog-detail' object.id %}">Cancel</a>
</form>
</div>
{% endblock %}
So, what I'm getting is that suppose 2 person jeff and ram are users so ram cannot update the posts of jeff and vice versa.
And if jeff views the post of ram, so he does not get the update and delete, so he cannot edit the post of ram but if jeff goes to "127.0.0.1:8000/post/9/delete" from "127.0.0.1:800/post/9",
So he get the confirm delete page and he can even delete his post.
How can I fix this bug in my project??????
you can use get_queryset() to restrict query in database
class PostUpdateView(UpdateView, LoginRequiredMixin, UserPassesTestMixin):
model = Post
success_url = "blog-home"
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def get_queryset(self):
pk = self.kwargs.get(self.pk_url_kwarg)
return self.model.objects.filter(pk=pk,user=self.request.user)
I am trying to display all of the objects from Company, in a Listview by using a for-loop on the template(landingpage.html) but it comes out empty. The tricky part for me is that the Model class (Company) comes from a different directory than where the listview is created. I am importing the Model class (Company) in views.py but it still shows up empty on the template.
Any ideas on why this might be?
event/views.py
from company.models import Company
class LandingpageView(ListView):
model = Event
template_name = "event/landingpage.html"
ordering = ['date']
context_object_name = 'event_list'
class LatestCompanyView(ListView):
model = Company
template_name = "event/landingpage.html"
event/urls.py
from .views import LatestCompanyView
urlpatterns = [
path('event/landingpage/', LatestCompanyView.as_view(), name='landingpage'),
]
event/landingpage.html
{% block content %}
<div class="row about-django">
<div class="col-6">
</div>
<div class="col-6">
<img class="about-django-img" src="{% static 'img/hero.png' %}">
</div>
</div>
<h1>Events</h1>
<div class="event-container">
{% for Event in event_list %}
<div class="row event-row">
<div class="col-4 event-col"><img src="{{ Event.eventImage.url}}" alt="{{ Event.eventTitle }}"></div>
<div class="col-4 event-col">
<h3 class="event-title">{{ Event.eventTitle }}</h3>
<div>Date: {{ Event.date }}</div>
<div>Location: {{ Event.location }}</div>
<div>Description: {{ Event.description }}</div>
</div>
<div class="col-2 event-col">Buy Tickets</div>
</div>
{% endfor %}
</div>
<h1>Latest</h1>
<div class="event-container">
{% for Company in company_list %}
<h3 class="event-title">{{ Company.description }}</h3>
{% empty %}
Nothing here!
{% endfor %}
</div>
{% endblock %}
company/models.py
class Company(models.Model):
user = models.ForeignKey(User, on_delete = models.CASCADE, default = None)
description = models.TextField()
def __str__(self):
return '{} {}'.format(self.user, self.description)
event/views.py:
class LatestCompanyView(ListView):
model = Company
template_name = "event/landingpage.html"
context_object_name = 'company_list'
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 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 %}">
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.