So I am doing the Django Practical Projects Tutorial and came very far.
I have this code:
def get_absolute_url(self):
return ('coltrane_entry_detail', (), {'year': self.pub_date.strftime("%Y"),
'month': self.pub_date.strftime("%b").lower(),
'day': self.pub_date.strftime("%d"),
'slug': self.slug })
get_absolute_url = models.permalink(get_absolute_url)
I get an Indentation Error.
If I indent than I get a working /weblog/ url but if I click on the "Read more" Links I always land on the same page /weblog/ and not /weblog/date/article.
If you know the tutorial, maybe you know the error if not here is all the files:
urls project:
from django.conf.urls.defaults import *
from Myproject.views import *
from django.views.generic.simple import direct_to_template
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
#Coltrane Project URlpatterns:
(r'^search/$', 'MyProject.search.views.search'),
(r'^weblog/$', include('coltrane.urls')),
Urls Coltrane:
from django.conf.urls.defaults import *
from coltrane.models import Entry
entry_info_dict = {
'queryset': Entry.objects.all(),
'date_field': 'pub_date',
}
#Coltrane Project URlpatterns:
urlpatterns = patterns('django.views.generic.date_based',
(r'^$', 'archive_index', entry_info_dict, 'coltrane_entry_archive_index'),
(r'^(?P<year>\d{4})/$', 'archive_year', entry_info_dict, 'coltrane_entry_archive_year'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/$', 'archive_month', entry_info_dict, 'coltrane_entry_archive_month'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/$', 'archive_day', entry_info_dict, 'coltrane_entry_archive_day'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$', 'object_detail', entry_info_dict, 'coltrane_entry_detail'),
)
Model:
import datetime
from django.contrib.auth.models import User
from django.db import models
from markdown import markdown
from tagging.fields import TagField
class Category(models.Model):
title = models.CharField(max_length=250, help_text='Maximum 250 characters.')
slug = models.SlugField(unique=True, help_text='This is the shortname that is created. Must be unique!')
description = models.TextField()
class Meta:
ordering = ['title']
verbose_name_plural = "Categories"
def __unicode__(self):
return self.title
def get_absolute_url(self):
return "/categories/%s/" %self.slug
class Entry(models.Model):
LIVE_STATUS = 1
DRAFT_STATUS = 2
HIDDEN_STATUS = 3
STATUS_CHOICES = (
(LIVE_STATUS, 'Live'),
(DRAFT_STATUS, 'Draft'),
(HIDDEN_STATUS, 'Hidden'),
)
#Core Fields.
title = models.CharField(max_length=250, help_text='Maximum 250 characters.')
excerpt = models.TextField(blank=True, help_text='A short summary of the entry. Optional!')
body = models.TextField()
pub_date = models.DateTimeField(default=datetime.datetime.now)
#Fields to store generated HTML.
excerpt_html = models.TextField(editable=False, blank=True)
body_html = models.TextField(editable=False, blank=True)
#Metadata
author = models.ForeignKey(User)
enable_comments = models.BooleanField(default=True)
featured = models.BooleanField(default=False)
slug = models.SlugField(unique_for_date='pub_date')
status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS, help_text="Only entries with live status will be publicly displayed")
#Categorization
categories = models.ManyToManyField(Category)
tags = TagField(help_text="Separate tags with spaces.")
class Meta:
ordering = ['pub_date']
verbose_name_plural = "Entries"
def __unicode__(self):
return self.title
def save(self, force_insert=False, force_update=False):
self.body_html = markdown(self.body)
if self.excerpt:
self.excerpt_html = markdown(self.excerpt)
super(Entry, self).save(force_insert, force_update)
def get_absolute_url(self):
return ('coltrane_entry_detail', (), {'year': self.pub_date.strftime("%Y"),
'month': self.pub_date.strftime("%b").lower(),
'day': self.pub_date.strftime("%d"),
'slug': self.slug })
get_absolute_url = models.permalink(get_absolute_url)
See the comments above, I found my error. I think the only way to close my own question is to answer it.
Related
I built this blog with django and everything is working except the blog post view count. On the page it adds 1 as instructed but adds 2 in django admin. Please let me know what I am doing wrongly
Models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth import get_user_model
User = get_user_model()
from ckeditor_uploader.fields import RichTextUploadingField
class Subscribe(models.Model):
email = models.EmailField()
class Comments(models.Model):
name = models.CharField('Name', max_length=120)
post_id = models.IntegerField(null=True)
email = models.EmailField()
website = models.URLField(max_length=200)
comment = models.TextField(blank=True)
date_created = models.DateTimeField(blank=True,null=True)
def publish(self):
self.date_created=timezone.localtime(timezone.now())
self.save()
class Category(models.Model):
name = models.CharField('Name', max_length=120)
slug = models.SlugField(default="", null=False)
def __str__(self):
return self.name
class Author(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
about = RichTextUploadingField()
image = models.ImageField(upload_to='images/', null=True)
slug = models.SlugField(default="", null=False)
views = models.IntegerField(default=0)
def __str__(self):
return self.user.username
def image_url(self):
if self.image and hasattr(self.image, 'url'):
return self.image.url
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
class Post(models.Model):
title = models.CharField('Post Title', max_length=120)
date = models.DateTimeField()
status = models.CharField(max_length = 10, choices = STATUS_CHOICES, default ='draft')
category = models.ForeignKey(Category,on_delete = models.SET_NULL, blank = True, null = True,)
author = models.ForeignKey(User,on_delete = models.SET_NULL, blank = True, null = True,)
details = RichTextUploadingField()
slug = models.SlugField(default="", null=False)
image = models.ImageField(upload_to='images/', null=True)
post_views = models.IntegerField(default=0)
class Meta:
ordering = ['-date']
def __str__(self):
return self.title
def image_url(self):
if self.image and hasattr(self.image, 'url'):
return self.image.url
Views.py
from django.shortcuts import render
from .models import Post
from .models import Comments
from .models import Category
from .models import Author
from .models import Subscribe
from django.http import JsonResponse
from django.utils import timezone
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Count
# DEFINING CONTEXTS DETAILS
posts = Post.objects.filter(status="published")
recentPosts = Post.objects.filter(status="published").order_by("-id")[:3]
sidebarPosts = Post.objects.filter(status="published").order_by("-id")[:5]
morePosts = Post.objects.filter(status="published").order_by("-id")[:2]
popularPosts = Post.objects.order_by("-post_views")[:3]
categoryList = Category.objects.annotate(nblog=Count('post')).values()
# VIEW FOR POST DETAILS PAGE
def details(request, slug):
thisPost = Post.objects.filter(slug=slug).first()
thisPost.post_views+=1
thisPost.save()
id = thisPost.id
author = thisPost.author
category = thisPost.category
postCategory = Category.objects.filter(name = category).first()
authorDetail = Author.objects.filter(user = author).first()
allComments = Comments.objects.filter(post_id = id).order_by("-date_created").values()
commentCount = len(Comments.objects.filter(post_id = id))
context = {
'details' : thisPost,
'postCategory' : postCategory,
'allComments' : allComments,
'count' : commentCount,
'authorDetail' : authorDetail,
'sidebarPosts' : sidebarPosts,
'morePosts' : morePosts,
'recentPosts' : recentPosts,
'popularPosts' : popularPosts,
'categoryList' : categoryList
}
return render(request,'markedia/details.html', context)
Urls
from django.urls import path
from markedia_blog import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.index, name="index"),
path('index', views.index, name="index"),
path('contact', views.contact, name="contact"),
path('details/<slug:slug>', views.details, name="details"),
path('comment', views.comment, name="comment"),
path('subscribe', views.subscribe, name="subscribe"),
path('blog', views.blog, name="blog"),
path('author/<slug:slug>', views.author, name="author"),
path('category/<slug:slug>', views.category, name="category"),
path('search', views.search, name="search"),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
ADMIN PAGE
Default = 0
Admin page
TEMPLATE PAGE
Post views is equal to 1 on template page
Post views is equal to 1 on template page
ADMIN PAGE AFTER VIEWING TEMPLATES PAGE
Post views is equal to 2 instead of 1
Post views is equal to 2 instead of 1
Could you tell me what i'm doing wrong??
Template page post views shows 1 but admin page shows 2
models.py
class Equipo(models.Model):
CODIGO = models.CharField(primary_key=True, max_length=5 )
DESCRIPCION = models.CharField(max_length=50, default='')
TITULO = models.FileField(upload_to = "Archivos/Titulos/", default='', blank=True)
admin.py
from django.contrib import admin
from .models import Equipo
class EquipoAdmin(admin.ModelAdmin):
list_display = ('CODIGO', 'DESCRIPCION', 'TITULO')
admin.site.register(Equipo, EquipoAdmin)
I need to see something like this
You can use below code result
# admin.py
list_display = ('title', 'description', 'embed_pdf', 'deadline')
def embed_pdf(self, obj):
try:
html = f'<iframe src="{obj.add_file.url}" width="200px" height="200px" frameborder="2"></iframe>'
formatted_html = format_html(html.format(url=obj.add_file.url))
return formatted_html
except Exception as e:
pass
embed_pdf.short_description = "File/Image"
admin.site.register(Order, OrderAdmin)
I am pretty new to Django Rest Framework and am trying to build an API that has various viewsets, and almost all are working properly except one.
In my viewset I have 3 ModelViewSet's: one to list all Inspections, one to show all completed (done) inspections and the last one to show all the undone inspections. The problem is that it is returning the list of all inspections correctly, but the other 2 return "detail: not found" even though I have instances of Inspections in my database.
Here is my Inspection Viewset:
from rest_framework.viewsets import ModelViewSet
from inspections.models import Inspection
from .serializers import InspectionSerializer
from rest_framework import generics
class InspectionViewSet(ModelViewSet):
queryset = Inspection.objects.all()
serializer_class = InspectionSerializer
class DoneInspectionsViewSet(ModelViewSet):
serializer_class = InspectionSerializer
def get_queryset(self):
queryset = Inspection.objects.all()
return queryset
class UndoneInspectionsViewSet(ModelViewSet):
serializer_class = InspectionSerializer
def get_queryset(self):
queryset = Inspection.objects.filter(done=False)
return queryset
Here's my Inspection Serializer:
from rest_framework.serializers import ModelSerializer
from inspections.models import Inspection
from properties.api.serializers import PropertySerializer
class InspectionSerializer(ModelSerializer):
property = PropertySerializer(many=False)
class Meta:
model = Inspection
fields = ('id', 'connected_check', 'category', 'property', 'date',
'done_date', 'done_by', 'staff', 'notes', 'done')
Here's the Inspection model:
from django.db import models
from check.models import Check
from properties.models import Property
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils import timezone
class Inspection(models.Model):
connected_check = models.ForeignKey(Check, on_delete=models.DO_NOTHING, null=True, blank=True, related_name='inspection_check')
category = models.ForeignKey(InspectionCategory, on_delete=models.DO_NOTHING)
property = models.ForeignKey(Property, on_delete=models.DO_NOTHING, related_name='inspection_property')
date = models.DateField()
done_date = models.DateField(blank=True, null=True)
done_by = models.ForeignKey(User, max_length=25, blank=True, null=True, related_name='inspection_done_by', on_delete=models.DO_NOTHING)
staff = models.ForeignKey(User, max_length=25, null=True, blank=True, related_name='inspection_staff', on_delete=models.DO_NOTHING)
notes = models.TextField(max_length=500, blank=True)
done = models.BooleanField(default=False)
def __str__(self):
return self.category.name
def get_absolute_url(self):
return reverse("inspections:details",kwargs={'pk':self.pk})
def get_category_name(self):
return self.category
def is_past_due(self):
return timezone.now() > self.date
def is_done(self):
self.done = True
self.done_date = timezone.now()
self.save()
And here are the urlpatterns and router:
router = routers.DefaultRouter(trailing_slash=False)
router.register(r'inspection', InspectionViewSet)
router.register(r'inspection/done', DoneInspectionsViewSet, basename='done-inspection')
router.register(r'inspection/undone', UndoneInspectionsViewSet, basename='undone-inspection')
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^admin/', admin.site.urls),
url(r'^inspections/', include(('inspections.urls','inspections'), namespace='inspections')),
]
urlpatterns += [
path('api/', include(router.urls)),
path('api/schema/', get_schema_view(
title = "DAPIMS",
description = "API for DAPIMS",
version = "1.0.0"
), name='openapi-schema'),
]
I have already tried to change the queryset and noticed that even if I just want to return all Inspection objects it still returns "detail: not found" even though if I run the interactive shell and execute the same queryset it returns the correct objects.
Here's an example of the return from the interactive shell
And this is what my Browsable API is returning
Thanks in advance!
I'm developing a simple blog to learn Django. I would like to have a path for each posts like this:
/category-1/title-post
/category-2/title-post
etc..
Below urls.py
from django.urls import include, path
from .views import CategoryList, PostList, SingleCategory, SinglePost, SingleTag, TagList
urlpatterns = [
path("", PostList.as_view(), name="list_post"),
path("<slug:slug>", SinglePost.as_view(), name="single_post"),
path("tags/", TagList.as_view(), name="list_tag"),
path("tags/<slug:slug>", SingleTag.as_view(), name="single_tag"),
path("categories/", CategoryList.as_view(), name="list_category"),
path("categories/<slug:slug>", SingleCategory.as_view(), name="single_category"),
]
And views.py
from django.shortcuts import render
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from .models import Category, Post, Tag
# Create your views here.
class CategoryList(ListView):
model = Category
context_object_name = 'category_list'
template_name = "list_category.html"
class SingleCategory(DetailView):
model = Category
template_name = "single_category.html"
class PostList(ListView):
model = Post
queryset = Post.objects.order_by('-id')
context_object_name = 'post_list'
template_name = "list_post.html"
paginate_by = 4
class SinglePost(DetailView):
model = Post
template_name = "single_post.html"
class TagList(ListView):
model = Tag
context_object_name = 'tag_list'
template_name = "list_tag.html"
class SingleTag(DetailView):
model = Tag
template_name = "single_tag.html"
Here models.py
class Category(models.Model):
category_name = models.CharField(
max_length=50,
)
slug = models.SlugField(
unique=True,
)
def __str__(self):
return self.category_name
def get_absolute_url(self):
return reverse("single_category", kwargs={"slug": self.slug})
class Post(models.Model):
title = models.CharField(
max_length=50,
)
slug = models.SlugField(
unique=True,
)
content = models.TextField()
tag = models.ManyToManyField(
Tag,
related_name="tag_set",
)
category = models.ForeignKey(
Category,
on_delete=models.CASCADE,
related_name="category_set",
)
highlighted = models.BooleanField(
default=False,
)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("single_post", kwargs={"slug": self.slug})
class Meta:
ordering = ['-id']
I don't understand how I can change the path "categories/" in "category-slug/". I would like to do a same thing for categories / , that must change in category-slug/post-slug.
How I can do this using the Class Based View?
You can define as many parameters in your URL as you like. Then you'll need to override get_object to get the relevant post by slug and category.
path('<slug:category_slug>/<slug:post_slug>', SinglePostByCategory.as_view(), 'single_post_by_category')
...
class SinglePostByCategory(DetailView):
def get_queryset(self):
return get_object_or_404(Post,
category__slug=self.kwargs['category_slug'],
slug=self.kwargs['post_slug']
)
Override the get_object.
class SinglePostByCategory(DetailView):
def get_object(self):
obj = get_object_or_404(Post, category__slug=self.kwargs['category_slug'], slug=self.kwargs['post_slug'] )
return obj
There is my simple blog model;
class Article(models.Model):
author = models.ForeignKey("auth.User",on_delete = models.CASCADE, verbose_name="Author")
title_en = models.CharField(max_length = 120, verbose_name="Title_En")
title_de = models.CharField(max_length = 120, verbose_name="Title_De")
category = models.ForeignKey('Category', on_delete = models.CASCADE, null=True, blank=True)
content_en = RichTextField(verbose_name="Content_En")
content_de = RichTextField(verbose_name="Content_De")
created_date = models.DateTimeField(auto_now_add=True, verbose_name="Created Date")
image = models.ImageField(blank=True, null=True, verbose_name="Add Photo (.jpg .png)")
slug = models.SlugField(unique=True, max_length = 130)
def __str__(self):
return self.title
I use url's with language like this;
domainname.com/en/
domainname.com/de/
For example, how can I show only the contents that belong to title_de and content_de in the domainname.com/de urls?
How can I do filtering with language? Is there an easy solution to this?
(I usage django 2.1.2. i try django-modeltranslation or others dont work this django version...)
Thanks...
You can create a descriptor class that wraps the translated fields e.g.,
from django.utils import translation
class TranslatedField:
def __init__(self, field_name):
self.partial_field_name = field_name
def __get__(self, obj, objtype):
return getattr(obj, self.field_name)
def __set__(self, obj, value):
return setattr(obj, self.field_name, value)
#property
def field_name(self):
language_code = translation.get_language()
rerurn self.partial_field_name + '_' + language_code
class Article(models.Model):
title_en = models.CharField(max_length=120)
title_de = models.CharField(max_length=120)
title = Translated Field('title')
Then you can do
article = Article.objects.create(
title_en='In english',
title_de='In German'
)
print(article.title) # 'In english'
translation.set_language('de')
print(article.title) # 'In German'
article.title = 'In German!'
print(article.title) # 'In German!'
translation.set_language('en')
print(article.title) # 'In english'
(Untested, so there may be typos)
I would use something out of the box like https://github.com/deschler/django-modeltranslation
Filtering based on keyward argument is one of the option for this problem.I would prefer to add a language field 'EN' or 'DE' rather than repeating same kind of title and content field and filtering based on that. For example,
Article Model can be like
class Article(models.Model):
LANGUAGE_TYPES = (
('EN', 'EN'),
('DE', 'DE'),
)
author = models.ForeignKey("auth.User",on_delete = models.CASCADE, verbose_name="Author")
title = models.CharField(max_length = 120, verbose_name="Title")
category = models.ForeignKey('Category', on_delete = models.CASCADE, null=True, blank=True)
content = RichTextField(verbose_name="Content")
created_date = models.DateTimeField(auto_now_add=True, verbose_name="Created Date")
image = models.ImageField(blank=True, null=True, verbose_name="Add Photo (.jpg .png)")
slug = models.SlugField(unique=True, max_length = 130)
language = models.CharField(
max_length=10, choices=LANGUAGE_TYPES)
def __str__(self):
return self.title
Our urls can be like
from django.urls import path
from .views import (ArticleView)
urlpatterns = [
path('article/<slug:type>/', ArticleView.as_view(), name='article'),
]
And Our view can be like
from rest_framework import views, status
from .serializers import ArticleSerializer
from .models import Article
class ArticleView(views.APIView):
def get(self, request):
article_language_type = self.kwargs.get('type', None)
articles = Article.objects.filter(language=article_language_type)
serializer = ArticleSerializer(articles, many=True)
if serializer.is_valid():
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)