Django page not found 404, Raised by: blog.views.blog_postDetailView - django

sometimes when i want to open the about page, the contact, create or blog
page this error comes: Raised by: blog.views.blog_postDetailView
i donnt know why, but I think it has to do sth with my urlpattterns
or the order of them . here my code.
appreciate your help and improvements
thanks a lot
mainurl
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from blog.views import AboutPageView, ContactPageView, blog_postCreateView
urlpatterns = [
url(r'^about/', AboutPageView.as_view(), name='about'),
url(r'^contact/', ContactPageView.as_view(), name='contact'),
url(r'^create/', blog_postCreateView.as_view(), name='blog_post_create'),
url(r'', include('blog.urls')),
url(r'^blog/', include('blog.urls')),
#admin and login
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('registration.backends.default.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
blog url
from django.conf.urls import url
from .views import blog_postListView, blog_postDetailView, blog_postCreateView
urlpatterns = [
url(r'^$', blog_postListView.as_view(), name='blog_post_list'),
url(r'^(?P<slug>[-\w]+)$', blog_postDetailView.as_view(), name='blog_post_detail'),
]
base html, the nav part
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
Home
</li>
<li>
About
</li>
<li>
Contact
</li>
<li>
Blog
</li>
<li>
{% if request.user.is_authenticated %}
<li>Logout</li>
{% else %}
<li>Login</li>
<li>Register</li>
{% endif %}
model
rom __future__ import unicode_literals
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.signals import pre_save, post_save
from django.utils.text import slugify
# Create your models here.
def upload_location(instance, filename):
#filebase, extension = filename.split(".")
#return "%s/%s.%s" %(instance.id, instance.id, extension)
return "%s/%s" %(instance.id, filename)
class blog_post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
title = models.CharField(max_length=120)
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
image = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field")
#height_field = models.PositiveIntegerField()
#width_field = models.PositiveIntegerField()
slug = models.SlugField(unique=True)
content = models.TextField()
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
def __unicode__(self):
return self.title
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("blog_post_detail", kwargs={"slug": self.slug})
def create_slug(instance, new_slug=None):
slug = slugify(instance.title)
if new_slug is not None:
slug = new_slug
qs = blog_post.objects.filter(slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_receiver, sender=blog_post)
views
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.views.generic import View
from django.views.generic.base import TemplateView, TemplateResponseMixin, ContextMixin
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.shortcuts import render
from django.utils.decorators import method_decorator
from .models import blog_post
from .forms import blog_postForm
# Create your views here.
class LoginRequiredMixin(object):
#classmethod
def as_view(cls, **kwargs):
view = super(LoginRequiredMixin, cls).as_view(**kwargs)
return login_required(view)
##method_decorator(login_required)
#def dispatch(self, request, *args, **kwargs):
# return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
class blog_postCreateView(LoginRequiredMixin, CreateView):
#model = blog_post
form_class = blog_postForm
template_name = "form.html"
#fields = ["title", "content"]
def get_success_url(self):
return reverse("blog_post_list")
# #method_decorator(login_required)
# def dispatch(self, request, *args, **kwargs):
# return super(MyView, self).dispatch(request, *args, **kwargs)
class blog_postListView(ListView):
model = blog_post
def get_queryset(self, *args, **kwargs):
qs = super(blog_postListView, self).get_queryset(*args, **kwargs).order_by("-timestamp")
return qs
class blog_postDetailView(DetailView):
model = blog_post
class AboutPageView(TemplateView):
template_name = "about.html"
class ContactPageView(TemplateView):
template_name = "contact.html"
updated urls
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from blog.views import AboutPageView, ContactPageView, blog_postCreateView
urlpatterns = [
url(r'^about/', AboutPageView.as_view(), name='about'),
url(r'^contact/', ContactPageView.as_view(), name='contact'),
url(r'^create/', blog_postCreateView.as_view(), name='blog_post_create'),
url(r'^categories/', include('blog.urls_categories')),
#url(r'', include('blog.urls')),
url(r'^blog/', include('blog.urls')),
#admin and login
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'', include('blog.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Put the below line in end of url_patterns list like
urlpatterns = [
#all other urls,
url(r'', include('blog.urls')),
]
OR
url(r'^blogdetail/', include('blog.urls')),

Related

Django redirect another view from another app form

contact/views.py
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import ContactForm
def contactView(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, from_email, ['admin#example.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
# return redirect('success')
return redirect('PostList') #another view from another app
return render(request, "contact.html", {'form': form})
# def successView(request):
# return HttpResponse('Success! Thank you for your message.')
contact/urls.py
from django.contrib import admin
from django.urls import path
from .views import contactView
urlpatterns = [
path('contact/', contactView, name='contact'),
# path('success/', successView, name='success'),
]
blog/views.py
from django.views import generic
from .models import Post, PostImage
# Create your views here.
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'index.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'
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['image_list'] = PostImage.objects.all()
# context['image_list'] = self.get_object().postimage_set.all()
context['image_list'] = PostImage.objects.filter(post__slug=self.kwargs.get('slug'))
return context
blog/urls.py
from . import views
from django.urls import path
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
]
I need the following in the SIMPLEST DRY manner possible; how do I write this redirect inside contact/views.py?
return redirect('PostList') #another view from another app
PostList is a class-based view from another app called blog. It is the homepage essentially.
for reference..
https://ordinarycoders.com/blog/article/django-messages-framework
In your project folder (eg, my_project/my_project) you should have a urls.py with something like this
path("admin/", admin.site.urls),
path("", include("blog.urls")),
path("", include("contact.urls"))
This allows django to look through all url files in the order listed. So long as all your url names and patterns are unique, then your view should be able to simply do
from django.shortcuts import redirect
from django.urls import reverse
return redirect(reverse('home'))
'home' being the name value of the ListView.
(NB: if you have various applevel urls.py files with path(''... django will take the first one it hits)

How to fix the problem of not showing the sitemap in django?

I created a sitemap as follows, but nothing is displayed inside the sitemap URL.
How can I fix the problem?
Thank you
setting.py
INSTALLED_APPS = [
'django.contrib.sitemaps',
]
sitemaps.py
from django.contrib.sitemaps import Sitemap
from django.shortcuts import reverse
from riposts.models import Posts
class RiSitemap(Sitemap):
priority = 0.5
changefreq = 'daily'
def get_queryset(self):
posts = self.kwargs.get('posts')
return Posts.objects.filter(status="p")
def lastmod(self, obj):
return obj.updated
def location(self, item):
return reverse(item)
urls.py
from django.contrib.sitemaps.views import sitemap
from .views import home_page
from riposts.sitemaps import RiSitemap
sitemaps = {
'posts':RiSitemap,
}
urlpatterns = [
path('', home_page, name="home"),
path("sitemap.xml", sitemap, {"sitemaps": sitemaps}, name="sitemap"),
]
sitemap image

Download BinaryFiled Data

how to download BinaryField Data/file using template. like we did for FileField.
<td><a href={{certificate.bytes.url}} download></a>
I past all url.py and view.py file below please look This may give extract view of my code. and please help me with this i am new to Django. ............................................................................................................................................................
url.py
from django.conf.urls.static import static
from django.conf.urls import url
from django.views.defaults import page_not_found
urlpatterns=[
path('',views.index, name = 'index'),
url(r'^list/$', views.list, name='list'),
url(r'^list/create$', views.certificate_create, name='certificate_create'),
url(r'^list/(?P<id>\d+)/update$', views.certificate_update, name='certificate_update'),
url(r'^list/(?P<id>\d+)/delete$', views.certificate_delete, name='certificate_delete'),
path('download',views.download, name = 'download'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
So, we need Django models which contains BinaryField for example.
models.py
class Person(models.Model):
name = models.CharField(max_length=55)
surname = models.CharField(max_length=55)
image = models.BinaryField()
class Meta:
db_table = 'person'
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('download/<int:pk>/', views.download, name='download'),
]
views.py
import io
from django.shortcuts import render
from django.http import FileResponse
from .models import Person
def index(request):
# there are listed all models.
persons = Person.objects.all()
return render(request, 'index.html', {'persons': persons})
def download(request, pk):
# this url is for download
try:
obj = Person.objects.get(pk=pk)
except Person.DoesNotExist as exc:
return JsonResponse({'status_message': 'No Resource Found'})
get_binary = obj.image
if get_binary is None:
return JsonResponse({'status_message': 'Resource does not contian image'})
if isinstance(get_binary, memoryview):
binary_io = io.BytesIO(get_binary.tobytes())
else:
binary_io = io.BytesIO(get_binary)
response = FileResponse(binary_io)
response['Content-Type'] = 'application/x-binary'
response['Content-Disposition'] = 'attachment; filename="{}.png"'.format(pk) # You can set custom filename, which will be visible for clients.
return response
index.html
{% for person in persons %}
{{ person.name }}<br />
{% endfor %}
This is solution to send binary file from server and download. All components are shown. Good luck !

include() got an unexpected keyword argument 'app_name'

i am making a blog application for my website with django-2.0
when i run server i see the following error
File "C:\Users\User\Desktop\djite\djite\djite\urls.py", line 7, in <module>
url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
TypeError: include() got an unexpected keyword argument 'app_name'
here is my main urls.py
from django.contrib import admin
from django.conf.urls import url,include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
]
and here's my blog/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>d{2})/(?P<post>
[-/w]+)/$', views.post_detail, name='post_detail'),
]
my views.py:
from django.shortcuts import render, HttpResponse, get_object_or_404
from blog.models import Post
def post_list(request): #list
posts=Post.published.all()
return render(request, 'blog/post/list.html', {'posts': posts})
def post_detail(request, year, month, day, post):
post =get_object_or_404(post, slog=post,
status='published',
publush__year=year,
publish__month=month,
publish__day=day)
return render (request, 'blog/post/detail.html', {'post':post})
models.py:
# -*- coding:utf-8 -*-
from django.db import models
from django.conf import settings
from django.utils import timezone
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.urls import reverse
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,
self).get_queryset().filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title =
models.CharField(max_length=255,verbose_name=_('title'),help_text=_('add
title'))
content = models.TextField(verbose_name=_('content'),help_text=_('write
here'))
publish = models.DateTimeField(default=timezone.now)
createtime = models.DateTimeField(_('create time'),auto_now_add=True,
auto_now=False,help_text=_('create time'))
updatetime = models.DateTimeField(_('update time'),auto_now_add=False,
auto_now=True,help_text=_('update time'))
author = models.ForeignKey(settings.AUTH_USER_MODEL,
verbose_name=_('author'),
on_delete=models.DO_NOTHING,help_text=_('choose author'))
slug = models.SlugField(unique=True, max_length=255,help_text=_('add
slug'))
status = models.CharField(max_length=10, choices=STATUS_CHOICES,
default='draft')
def __unicode__(self):
return self.title
def __str__(self):
return self.title
class Meta:
ordering = ('-publish',)
verbose_name = _('Post')
verbose_name_plural = _('Posts')
def get_absolute_url(self):
return reverse('blog:post_detail', args=[self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug])
also my views.py has a problem that i don't think that's related to my current error, when i delete
namespace='blog', app_name='blog'
from this line in main urls.py
url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
the server runs but when i go to this directory:
http://localhost:8000/blog/
i see this error
AttributeError at /blog/
type object 'Post' has no attribute 'published'
it says that this line of code has problem in views.py
posts=Post.published.all()
Using app_name with include is deprecated in Django 1.9 and does not work in Django 2.0. Set app_name in blog/urls.py instead.
app_name = 'blog'
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
...
]
Then change the include to:
url(r'^blog/', include('blog.urls')),
You don't need namespace='blog', as it will default to the application namespace anyway.
The second error is unrelated. You have forgotten to instantiate your custom manager on the model.
class Post(models.Model):
...
published = PublishedManager()
In Django 2.0 app_name, will not support :
Use of project URLs:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path(r'blog/', include('blog.urls')),//use this
]

Why does my dead simple Django app keep crashing python on my mac 10.6.4?

views.py
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.shortcuts import get_list_or_404
from django.template.context import RequestContext
from articles.models import Article
def index(request):
articles = get_list_or_404(Article)
return render_to_response(
'articles/index.html',
{"articles": articles},
context_instance=RequestContext(request),
mimetype="application/xhtml+xml")
def article(request, article_id):
article = get_object_or_404(Article, pk=article_id)
return render_to_response(
'articles/article.html',
{"article": article},
context_instance=RequestContext(request),
mimetype="application/xhtml+xml")
models
from django.db import models
from django.contrib.auth.models import User
import datetime
class Article(models.Model):
"""
Article model
"""
title = models.CharField(blank=True, max_length=200)
slug = models.SlugField()
body = models.TextField(blank=True)
created = models.DateTimeField(blank=True, default=datetime.datetime.now)
author = models.ForeignKey(User)
def __unicode__(self):
return "%s" % (self.title)
#property
def handle(self):
return self.slug
urls
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(
r'^$',
'articles.views.index',
name="articles_index"
),
url(
r'^article/(?P<article_id>\d*)$',
'articles.views.article',
name="article_view",
),
)
root urls
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
from settings import PROJECT_ROOT
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
)
urlpatterns += patterns('',
(r'^articles/', include('articles.urls')),
)
urlpatterns += patterns('',
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': PROJECT_ROOT + "/media"}),
)
Would you need to see more?
I had a theory that the word 'Article' might have conflicted with something, tho I tried renaming that to no avail.
This is supposed to be just a little 'play app' that I'm learning on. But now I'm quite stuck.
Running: python manage.py runserver_plus
http://127.0.0.1:8000/admin (views work ok)
http://127.0.0.1:8000/articles (crashes python everytime)
Quite a hair pulling exercise... help very much appreciated
edit
the error report:
http://dpaste.org/8Fzx/
Thank you!
Answer: self referencing template!