I am working on a blog django app.
I have list of posts and a post detail pages.
when I click on a post title in the list should takes to the post detail page.
views.py
from django.shortcuts import render, get_list_or_404
from .models import Post
def list_of_post(request):
post = Post.objects.all()
template = 'blog/post/list_of_post.html'
context = {'post': post}
return render(request, template, context)
def post_detail(request, slug):
post = get_list_or_404(Post, slug=slug)
template = 'blog/post/post_detail.html'
context = {'post': post}
return render(request, template, context)
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.list_of_post, name='list_of_post'),
url(r'^(?P<slug>[-\w]+)/$', views.post_detail, name='post_detail')
]
models.py
from django.db import models
from django.utils import timezone
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published')
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250)
content = models.TextField()
seo_title = models.CharField(max_length=250)
seo_description = models.CharField(max_length=160)
author = models.ForeignKey(User, related_name='blog_posts')
published = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=9, choices=STATUS_CHOICES, default='draft')
def get_absolute_url(self):
return reverse('blog:post_detail', args=[self.slug])
def __str__(self):
return self.title
list_of_post.html
{% extends 'blog/base.html' %}
{% block title %}List of blog post{% endblock %}
{% block content %}
{% for posts in post %}
<h2>{{ posts.title }}</h2>
<p>Written by {{ posts.author }} on {{ posts.published }}</p>
<hr>
{{ posts.content|truncatewords:40|linebreaks }}
{% endfor %}
{% endblock %}
for some reason the url doesn't work. instead shows 404 that looks like this :
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/blog/practice-title/%EF%BB%BF
Using the URLconf defined in cms.urls, Django tried these URL patterns,in this order:
^admin/
^blog/ ^$ [name='list_of_post']
^blog/ ^(?P<slug>[-\w]+)/$ [name='post_detail']
The current URL, blog/practice-title/, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
and ideas?
Related
I am using MVT in django. I am using generic CBV (listview, detailview). here are my codes
Here is model.py
from django.db import models
class Singers(models.Model):
name= models.CharField(max_length=256)
age= models.IntegerField()
gender= models.CharField(max_length=10)
class Albums(models.Model):
name= models.CharField(max_length=256)
singer=models.ForeignKey(Singers, on_delete=models.CASCADE)
view.py
from django.views import generic
from core.models import Albums, Singers
#in generic view instead of functions, we use classes
class AlbumView(generic.ListView):
model = Albums
template_name = 'index.html'
paginate_by = 10
def get_queryset(self):
return Albums.objects.all()
class DetailView(generic.DetailView):
model = Albums
template_name = 'detailview.html'
Here are urls.py
from django.urls import path
from core.views import AlbumView, DetailView
urlpatterns = [
path('album/', AlbumView.as_view()),
path('album/detail/<pk>/', DetailView.as_view())
]
Here is index.html
{% block content %}
<h2>Albums</h2>
<ul>
{% for albums in object_list %}
<li>{{ albums.name }}</li>
{% endfor %}
</ul>
{% endblock %}
here is detailview.html
{% block content %}
<h1>name: {{Albums.name}}</h1>
<p><strong>Singer: {{Albums.Singer}}</strong></p>
{% endblock %}
The detail view is not working fine. It is not fetching the respective name of the album and singer details.
Suggest me what should i do?
Try this
{% block content %}
<h1>name: {{object.name}}</h1>
<p><strong>Singer: {{object.singer.name}}</strong></p>
{% endblock %}
class DetailView(generic.DetailView):
model = Albums
template_name = 'detailview.html'
This is not working you have to get first context like this
def get_context_data(self, **kwargs):
// Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
// Add in a QuerySet of all the books
context['Album_list'] = Albums.objects.all()
return context
And you can do as well
context_object_name = 'publisher'
queryset = Publisher.objects.all()
I have two types of users in my model. And I am trying to get only one type of user to display on my HTML page. I am new to Django, so I am having some small problems. And place try to explain in a comment
This is my models.py file:
class CustomKorisnici(AbstractUser):
MAJSTOR = '1'
KORISNIK = '2'
USER_TYPE_CHOICE = (
(MAJSTOR, 'majstor'),
(KORISNIK, 'korisnik')
)
user_type = models.CharField(max_length=100,blank=True,choices=USER_TYPE_CHOICE)
username = models.CharField(max_length=100,unique=True)
last_name = models.CharField(max_length=100)
first_name = models.CharField(max_length=100)
phone_number = models.CharField(max_length=100)
profile_image = models.ImageField(null=True, upload_to="images/",
default='korisnici/static/post_user/images/profile_image.png')
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
email = models.EmailField(max_length=100,unique=True)
bio = models.TextField(default=" ")
After this a setup my view.py file for filtering data from the database:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post, TaskCategory,CustomKorisnici
from .forms import PostForm, updatePost
from django.urls import reverse_lazy,reverse
from django.http import HttpResponseRedirect
class MajstoriView(ListView):
model = CustomKorisnici
context_object_name = 'majstori'
template_name = 'majstori_view.html' # html stranica na kojoj ce podaci biti prikazani
def get_queryset(self): # get_queryset biblioteka iz paythona
return CustomKorisnici.objects.filter(user_type="MAJSTORI")
A setup URL after that:
from django.urls import path
from . import views
from .views import MajstoriView
urlpatterns = [
path('Majstori/',MajstoriView.as_view(), name="majstori_view"),
]
And finally my HTML page.
{% block content %}
<div class="container>
{% for majstori in majstori %}
User name: {{ majstori.username }}
Category: {{ majstori.first_name }}
Tools: {{ majstori.last_name }}
Budget: {{ majstori.bio }}</strong></p>
{% endfor %}
</div>
{% endblock %}
I am trying only to display user with user_tayp = "MAJSTOR"
after researching for hours I cannot get rid of this error, I hope someone can help me.
Models:
class Puja(models.Model):
seller = models.OneToOneField(Seller, on_delete=models.CASCADE)
user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True,null=True)
title = models.CharField(max_length=100)
video = models.FileField(blank=True)
photo = models.ImageField(blank=True)
published_date = models.DateTimeField("Published: ",default=timezone.now())
bidding_end = models.DateTimeField()
starting_price = models.IntegerField(default=1)
#slug = models.SlugField(null=True)
def __str__(self):
return str(self.title)
#def get_absolute_url(self):
# return reverse('bidding_list_detail', args=[str(self.id)])
#slug time
def get_absolute_url(self):
return reverse('bidding_list_detail',args={'id': self.id})
Views:
class bidding_list(ListView):
model = Puja
template_name = 'bidding_templates/bidding_list.html'
"""return render(request= request,
template_name='bidding_templates/bidding_list.html',
context = {"Pujas": Puja.objects.all})"""
class bidding_list_detail(DetailView):
model = Puja
template_name = 'bidding_templates/bidding_list_detail.html'
urls:
path('admin/', admin.site.urls),
path("bidding_list/", bidding_list.as_view(), name="bidding_list"),
path('<int:pk>', bidding_list_detail.as_view(), name='bidding_list_detail'),
admin:
class PujaAdmin(admin.ModelAdmin):
list_display = ('seller','title','video','photo','published_date','bidding_end','starting_price')
admin.site.register(Puja,PujaAdmin)
template 1:
{% extends 'header.html' %}
{% block content %}
<h1>Pujas</h1>
{% for Puja in object_list %} <!--object_list-->
<ul>
<li> {{ Puja.title }} </li>
</ul>
{% endfor %}
{% endblock %}
template 2:
{% extends 'header.html' %}
{% block content %}
<div>
<h2>{{ object.title }}</h2>
<p>{{ object.seller }}</p>
</div>
{% endblock %}
Note that, whenever I remove <a href="{{ Puja.get_absolute_url }}"> from the first template, the objects "puja" in the model get properly displayed on the template, but I cannot access them. They normally exist on the admin panel, but not displayed on the website directly.
Thank you very much on advance and stay healthy.
edit 1: Here is the urls.py directly from the app created by django. To be more specific, I created after the project a new app called "main" in which I programmed all the project, including all the code on this question except the edit.
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
#from django.config import settings
#from django.config.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main.urls')),
#path('', include('model.urls')),
#path('', include('blog.urls')),
#path('', include('photo.urls')),
#path('', include('video.urls')),
] # +static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I guess the problem is this line - return reverse('bidding_list_detail',args={'id': self.id}), you are passing id as a string but trying to match with int in url.Try following return reverse ('bidding_list_detail',args=[self.id])
I'm sure this is a very basic question but I have a OneToMany Relationship and I wish to list all the associated children on a page. Here's what i have so far.
Model File
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=100)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse ('blog-post' , kwargs = {'pk': self.pk})
class Paragraph(models.Model):
content = models.TextField(default='')
post = models.ForeignKey(Post,default='', on_delete=models.CASCADE)
def __str__(self):
return self.content
class Subtitle(models.Model):
subtitle = models.CharField(max_length=100,default='')
post = models.ForeignKey(Post,default='', on_delete=models.CASCADE)
def __str__(self):
return self.subtitle
View
model = Post
template_name = 'blog/post.html'
context_object_name = 'post'
HTML FILE
{%block content%}
{% if post.author == user %}
Edit
Delete
{% endif %}
<div class = 'content'>
<h2>{{post.title}}</h2>
<!-- I want to show Subtitle here--><p></p>
<!-- I want to show Paragraph here--><p></p>
<h3>By: {{post.author}} on {{post.date_posted}}</h3>
</div>
{% endblock content %}
Isn't it's just {% for subtitle in post.subtitle_set.all %} {{ subtitle }} {% endfor %} and same for paragraph? – Charnel Feb 23 at 21:42
I have a working HTML view and a working detail API RUD view for some simple model objects. Within the HTML view, elements are listed that have their own API RUD view. I'd like to be able to link each list element in the HTML to it's own API RUD view.
Below is my models.py:
class Hints(models.Model):
text = models.TextField(max_length=255)
author = models.CharField(max_length=20)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.text)
def timestamp_pretty(self):
return self.timestamp.strftime('%b %d %Y')
def get_api_url(self, request=None):
return api_reverse("api-hints1:hints-rud", kwargs={'pk': self.pk}, request=request)
Below is my views.py:
class HTMLAPIView(viewsets.ViewSet):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'base.html'
serializer_class = HTMLSerializer
def list(self, request):
queryset = Hints.objects.order_by('pk')
paginator = Paginator(queryset, 5) # Show 5 items per page
page = request.GET.get('page')
queryset1 = paginator.get_page(page)
return Response({'queryset1': queryset1})
class HintsListApiView(mixins.CreateModelMixin, generics.ListAPIView):
lookup_field = 'pk'
serializer_class = HintsSerializer
def get_queryset(self):
qs = Hints.objects.all()
query = self.request.GET.get("q")
if query is not None:
qs = qs.filter(
Q(text__icontains=query)|
Q(author__icontains=query)
).distinct()
return qs
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
def get_serializer_context(self, *args, **kwargs):
return {"request": self.request}
class HintsRudView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'pk'
serializer_class = HintsSerializer
def get_queryset(self):
return Hints.objects.all()
def get_serializer_context(self, *args, **kwargs):
return {"request": self.request}
My urls.py:
from .views import HintsRudView, HintsListApiView, HTMLAPIView
from . import views
from django.contrib import admin
from django.conf.urls import url, include
from rest_framework import routers, serializers, viewsets
urlpatterns = [
url(r'^(?P<pk>\d+)$', HintsRudView.as_view(), name='hints-rud'),
url(r'^$', HintsListApiView.as_view(), name='hints-list'),
url(r'^html/', HTMLAPIView.as_view({'get': 'list'}), name='html' )
]
And my relevant HTML code:
As you can see this was my attempt <li>{{ query }}</li>. Unfortunately, I get the following error:
Reverse for 'hints-rud' not found. 'hints-rud' is not a valid view function or pattern name.
{% load staticfiles %}
{% load static %}
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="{% static 'hints1/style.css' %}">
<link href="https://fonts.googleapis.com/css?family=Fjalla+One|Montserrat|Noto+Serif|Nunito|Oswald|Teko" rel="stylesheet">
</head>
<body>
<h1>Handy Dev Hints</h1>
<ul>
{% for query in queryset1 %}
<li>{{ query }}</li>
{% endfor %}
</ul>
<br/>
<br/>
<div class="pagination">
<span class="step-links">
<center>
{% if queryset1.has_previous %}
« First
Previous
{% endif %}
{% if queryset1.has_next %}
Next
Last »
{% endif %}
<br/>
<br/>
<span class="current">
Page {{ queryset1.number }} of {{ queryset1.paginator.num_pages }}
</span>
</center>
</span>
</div>
</body>
</html>
Not sure where to go from here. This doesn't seem like it should be a difficult problem. I've tried removing some $ from the urls.py but it made little difference. I've also tried other views and patterns besides hints-rud but all come back with the same error.
You need to use the namespace, exactly as you do in the get_api_url method.
<a href="{% url 'api-hints1:hints-rud' pk=pk %}">