Django Markdown Editor does not show up - python

I'm creating my very first Django application (I'm also a novice at Python, so the problem could be anywhere.)
I'm following this tutorial step by step, to get the HTML editor at 5:53 (here), however I still get the default TextField at http://127.0.0.1:8000/admin/blog/entry/add/
Any help on diagnosing the problem would be appreciated.
Thanks!
My Files :
projects/qblog/blog/admin.py :
from django.contrib import admin
from . import models
from django_markdown.admin import MarkdownModelAdmin
class EntryAdmin(MarkdownModelAdmin):
list_display = ("title" , "created")
prepopulated_fields = {"slug" : ("title", )}
admin.site.register(models.Entry, EntryAdmin)
projects/qblog/qblog/urls.py :
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^markdown/', include("django_markdown.urls")),
)
projects/qblog/blog/models.py :
from django.db import models
# Create your models here.
class EntryQuerySet(models.QuerySet):
def published(self):
return self.filter(publish=True)
class Entry(models.Model):
title=models.CharField(max_length=200)
body = models.TextField()
slug = models.SlugField(max_length=200,unique = True)
publish = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add = True)
modified = models.DateTimeField(auto_now = True)
objects = EntryQuerySet.as_manager()
def __str__(self):
return self.title
class Meta:
verbose_name = "Blog Entry"
verbose_name_plural = "Blog Entries"
ordering = ["-created"]
projects/qblog/qblog/settings.py :
"""
Django settings for qblog project.
Generated by 'django-admin startproject' using Django 1.9.dev20150210173028.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'secretkey'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'django_markdown',
]
MIDDLEWARE_CLASSES = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
]
ROOT_URLCONF = 'qblog.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'qblog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/
STATIC_URL = '/static/'

In the video's comments you can get the answer. Modify the next files:
models.py
from django_markdown.models import MarkdownField
...
body = MarkdownField()
settings.py
...
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
# Markdown
MARKDOWN_EDITOR_SKIN = 'simple'
urls.py
...
from yourapp import settings
if settings.DEBUG:
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
In shell run:
python manage.py collectstatic

I have same problem. However, when I add Mr. iago1460's code without the urls.py part,after I run:
python manage.py collectstatic,
the django_markdown can work ,I use python 2.7 and django 1.8 version
the urls.py code here
from django.conf.urls import include, url
from django.contrib import admin
#import settings
#if settings.DEBUG:
#from django.conf.urls.static import static
#urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urlpatterns = [
# Examples:
# url(r'^$', 'cblog.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^markdown/', include("django_markdown.urls")),
url(r'^',include('blog.urls')),
]
here is my project files ,my project name is cblog ,app is blog:
djtest/cblog/cblog:
__init__.py __init__.pyc settings.py settings.pyc urls.py urls.pyc wsgi.py wsgi.pyc
djtest/cblog:
blog cblog db.sqlite3 manage.py static

Yeah i found this problem too when i was trying qblog tutorial. i'm using Python 3.4 and Django 1.8.1, But on the step to install markdown package, i decide to change the package into Django CKEditor.
Visit https://pypi.python.org/pypi/django-ckeditor to install.
After CKEditor has been installed properly, if you find the problem in import forms.util flattat when you are running the server.
Change your widgets.py under ckeditor folder (on windows environment the directory is under C:\Python34\Lib\site-packages\ckeditor), then change the line :
from django.forms.util import flatatt
to
from django.forms.utils import flatatt
Follow in how to use CKEditor then implement it on your qblog.
The result will be like this :

Try this easier way:
in admin.py :
from django_markdown.admin import MarkdownModelAdmin
from django_markdown.widgets import AdminMarkdownWidget
from django.db.models import TextField
class EntryAdmin(MarkdownModelAdmin):
... #your_code
formfield_overrides = {TextField: {'widget': AdminMarkdownWidget}}
admin.site.register(models.Entry, EntryAdmin)

This happens when you are using python 2x
Now,what happens is that the stylesheets and javascript are not loaded
So what you can do is:
from django_markdown.widgets import AdminMarkdownWidget
from django.db.models import TextField
class EntryAdmin(MarkdownModelAdmin):
list_display = ("title", "created")
prepopulated_fields = {"slug": ("title",)}
# Next line is a workaround for Python 2.x
formfield_overrides = {TextField: {'widget': AdminMarkdownWidget}}
and this will work!!!!!!!!!!!!!

Python 2.x You need add that:
formfield_overrides = {TextField: {'widget': AdminMarkdownWidget}}

Related

Not showing Media images in Django however Static files work

I am out of my depth and would like to ask you about my challenge with some images that won't load on my project. Images and CSS from the static folder get loaded successfully. But my images from the media folder are what is not showing up with error
GET /images/uploads/2021/02/11/pexels-carly-jamieson-1478450.jpg HTTP/1.1" 404
I have already done python manage.py collectstatic plenty of times. For media files I use ckeditor image uploader. Files get uploaded fine, I can see them in the media folder. The thing is, this used to work before and now it just does not.
settings.py
import os
from pathlib import Path
from decouple import config
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = config('DEBUG', default=False, cast=bool)
ALLOWED_HOSTS = ['localhost']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#my apps
'blog',
'ckeditor',
'ckeditor_uploader',
]
CKEDITOR_UPLOAD_PATH = "uploads/"
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'portfolio.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'portfolio/templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'portfolio.wsgi.application'
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Heroku settings
cwd = os.getcwd()
if cwd == '/app' or cwd[:4] == '/tmp':
import dj_database_url
DATABASES = {
'default': dj_database_url.config(default='postgres://localhost')
}
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
MEDIA_URL = '/images/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
STATIC_ROOT = os.path.join(BASE_DIR, 'assets/')
urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
app_name = "blog"
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls', namespace='blog')),
path('ckeditor/', include('ckeditor_uploader.urls'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py:
from django.db import models
from portfolio.utils import unique_slug_generator
from django.db.models.signals import pre_save
#from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField
class BlogPost(models.Model):
"""A blog entry"""
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=100, null=True, blank=True)
intro = models.TextField(blank='True')
text = RichTextUploadingField()
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-date_added']
def __str__(self):
return self.title
def slug_generator(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = unique_slug_generator(instance)
pre_save.connect(slug_generator, sender=BlogPost)
class Contact(models.Model):
name = models.CharField(max_length=255)
email = models.EmailField()
subject = models.CharField(max_length=255)
message = models.TextField()
def __str__(self):
return self.name
I've tried different suggestions from SO with no luck. I want to sincerely ask all of you Django masters for your expertise and show me the way to make the images I upload to display. I really appreciate your kindness and generosity!
settings.py:
CKEDITOR_UPLOAD_PATH = 'uploads/'
CKEDITOR_IMAGE_BACKEND = "pillow"
CKEDITOR_THUMBNAIL_SIZE = (500, 500)
CKEDITOR_IMAGE_QUALITY = 40
CKEDITOR_BROWSE_SHOW_DIRS = True
CKEDITOR_JQUERY_URL = 'http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'
set image backend as pillow

Python Django - change_view() missing 1 required positional argument: 'object_id'

I am new in Django Framework and currently working on first project. I made a simple contact form it takes data from users and save it into database. Everything is working right. But when I login into my admin panel and go into the Contacts and click on the data that I received. I am getting error "change_view() missing 1 required positional argument: 'object_id'".
my admin.py
from home.views import contact
from django.contrib import admin
from home.models import Contact
# Register your models here.
admin.site.register(Contact)
my models.py
from django.db import models
# Create your models here.
class Contact(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField()
phone = models.CharField(max_length=10)
desc = models.TextField()
my views.py
from home.models import Contact
from django.shortcuts import render, HttpResponse
from home.models import models
# Create your views here.
def home(request):
return render(request, 'home.html')
def about(request):
return render(request, 'about.html')
def projects(request):
return render(request, 'projects.html')
def contact(request):
if request.method=='POST':
print('This is POST')
name = request.POST['name']
email = request.POST['email']
phone = request.POST['phone']
desc = request.POST['desc']
# print(name, email, phone, desc)
contact = Contact(name=name, email=email, phone=phone, desc=desc)
contact.save()
print('DAta has been written into the Database')
# return HttpResponse("This is My Contact")
return render(request, 'contact.html')
my settings.py
"""
Django settings for pwhTutorials project.
Generated by 'django-admin startproject' using Django 3.1.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '-snip-'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'home',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'pwhTutorials.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'pwhTutorials.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
my urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name = 'home'),
path('about/', views.about, name = 'about'),
path('projects/', views.projects, name = 'projects'),
path('contact/', views.contact, name = 'contact'),
]
Project's urls.py
"""
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("home.urls"))
]
I am new in Django Framework and currently working on first project. I made a simple contact form it takes data from users and save it into database. Everything is working right. But when I login into my admin panel and go into the Contacts and click on the data that I received. I am getting error "change_view() missing 1 required positional argument: 'object_id'".
This is the image link https://ibb.co/LScd2Mb
You missed """ at the top of your projects urls.py. Please correct, hope this will solve your problem.

Import problem in pycharm with django tutorial

Yesterday I started learning django with this tutorial:
https://www.youtube.com/watch?v=IMG4r03G6g8
But I am getting an Import Error here:
file: django_1/src/dj30/urls.py
from django.contrib import admin
from django.urls import path
from posts.views import post_list_view # ERROR LINE
urlpatterns = [
path('admin/', admin.site.urls),
path('posts/', post_list_view)
]
This is my directory tree:
I assume that the Import Error occurs because I am trying to import posts.views.post_list_view from posts/views.py into dj30/urls.py which is in another directory. How does the guy in the tutorial do it? I am positive that I followed the tutorial correctly (I did it twice). Maybe there is a problem with venv because I am using PyCharm (com) and he is not.
Here are relevant files that were edited during the tutorial:
django/src/dj30/settings.py:
"""
Django settings for dj30 project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'z=5t$_w+c#k3u+e1c-1tn6xoolrm#*ki*##kh1u_*=rmwxtk!s'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'posts'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'dj30.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'dj30.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
django_1/src/dj30/urls.py:
from django.contrib import admin
from django.urls import path
from posts.views import post_list_view
urlpatterns = [
path('admin/', admin.site.urls),
path('posts/', post_list_view)
]
django_1/src/posts/models.py:
from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()
def __str__(self):
return self.title
django_1/src/posts/admin.py:
from django.contrib import admin
# Register your models here.
from .models import Post
admin.site.register(Post)
django_1/src/posts/views.py:
from django.shortcuts import render
from .models import Post
# Create your views here.
def post_list_view(request):
post_objects = Post.objects.all()
context = {
'post_objects': post_objects
}
return render(request, 'posts/index.html', context)
django_1/src/posts/templates/posts/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>This is the list of all posts.</h1>
</body>
</html>
Edit:
When I try to run urls.py this error occurs:
Traceback (most recent call last):
File "C:/Users/Artur/Desktop/django_1/src/dj30/urls.py", line 4, in <module>
from posts.views import post_list_view
ModuleNotFoundError: No module named 'posts'
Running manage.py with runserver produces this website:
When I comment out:
from posts.views import post_list_view
and
path('posts/', post_list_view)
the site is shown correctly:
Edit_2:
Going to http://127.0.0.1:8000/posts/ as suggested shows this:
Edit_3:
Changing urls.py to:
from django.contrib import admin
from django.urls import path
from posts.views import post_list_view
urlpatterns = [
path('admin/', admin.site.urls),
path('posts/', post_list_view),
path('/', post_list_view)
]
produces this output:
C:\Users\Artur\Desktop\django_1\venv\Scripts\python.exe C:/Users/Artur/Desktop/django_1/src/manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified some issues:
WARNINGS:
?: (urls.W002) Your URL pattern '/' has a route beginning with a '/'. Remove this slash as it is unnecessary. If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'.
System check identified 1 issue (0 silenced).
October 18, 2020 - 09:44:14
Django version 3.1.2, using settings 'dj30.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
and this website:
Pycharm is marking the line red, because it is not aware of the application base directory. You need to click on 'src' and mark the directory as a sources root for this error to vanish.
Application is giving "file not found error" because in your main url file "dj30/urls.py" you do not specify the path for "", you just have "posts/" and "admin/" there. To solve it, you can simply add another path:
from django.contrib import admin
from django.urls import path
from posts.views import post_list_view # ERROR LINE
urlpatterns = [
path('admin/', admin.site.urls),
path('posts/', post_list_view),
path('', post_list_view),
]
But I would not consider it an error.
And I don't believe that you would ever want to run 'urls.py' file by its own.
Try this:
from django.contrib import admin
from django.urls import path
from posts import views as posts_views
urlpatterns = [
path('admin/', admin.site.urls),
path('posts/', posts_views.post_list_view)
]

Django: Getting 404 Error After Adding Views, Models and URLs Correctly

I am a beginner in Django. Right now, I am doing a simple app, called GameReview. It will allow the users to add the reviews of their favorite games. Right now, I am facing a 404 error.
It looks like this:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/gamereview/
Using the URLconf defined in gamerevs.urls, Django tried these URL patterns, in this order:
admin/
[name='hw']
gamereview [name='gamelist']
The current path, gamereview/, didn't match any of these.
Here are my codes of models.py inside gamereview folder:
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Tag(models.Model):
label = models.CharField(max_length=20)
def __str__(self):
return self.label
class Game(models.Model):
title = models.CharField(max_length=100)
developer = models.CharField(max_length=100)
platform = models.CharField(max_length=50, default='null')
label_tag = models.ManyToManyField(Tag)
slug = models.SlugField(max_length=150, default='null')
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)
class Review(models.Model):
game = models.ForeignKey(Game, on_delete=models.CASCADE)
review = models.CharField(max_length=1000)
date = models.DateField(auto_now=True)
slug = models.SlugField(max_length=150, default='null')
def __str__(self):
return self.review
def save(self):
super(Review, self).save()
self.slug = '%i-%s' % (
self.id, slugify(self.game.title)
)
super(Review, self).save()
Here are my codes of urls.py inside gamereview folder:
from . import views
from django.urls import path
urlpatterns = [
path('gamereview', views.gamelist, name='gamelist'),
]
Here are my codes of views.py inside gamereview folder:
from django.shortcuts import render
def gamelist(request):
context_dict = {'via': "Using template"}
return render(request, 'gamereview/gamelist.html', context_dict)
Here are the codes of settings.py in gamerevs folder:
"""
Django settings for gamerevs project.
Generated by 'django-admin startproject' using Django 2.2.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'su9+iji4y-5+ddebbavou+166_p2ph1n2cls3a^x_n9o6yl1nq'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'gamereview.apps.GamereviewConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'gamerevs.urls'
TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['/gamerevs/', TEMPLATE_PATH],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'gamerevs.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_PATH = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = [
STATIC_PATH,
]
Here are my codes of urls.py under gamerevs folder:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('helloworld.urls')),
path('', include('gamereview.urls')),
]
Here are my codes of gamelist.html located inside gamereview folder of the templates folder.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Gamelist</title>
</head>
<body>
<h1>This is Game List Page</h1>
<strong>{{ via }}</strong><br />
<img src="{% static "images/Super_Mario_Odyssey.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
</body>
</html>
I thought that logging into Django admin and adding new games and reviews from there would fix the issue. However, after doing it, I am still getting the 404 error.
urlpatterns = [
path('gamereview', views.gamelist, name='gamelist'),
]
The URL path without trailing / (slash) will give 404 for URL ending with trailing slash.
gamereview will match only gamereview
gamereview/ will match gamereview/ and will redirect gamereview to gamereview/ matching both the types of URLs.
I recommend trailling slash in every URL path (in Django).
# You need to add your app name in your settings.py file 'INSTALLED_APPS'
INSTALLED_APPS = [
'gamereview.apps.GamereviewConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'gamereview',
]
Change urls.py file's (inside gamreview folder) content by;
urlpatterns = [
path('', views.gamelist, name='gamelist'),
]
and change urls.py file's (inside project directory) content to following;
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('helloworld.urls')),
path('gamereview/', include('gamereview.urls')),
]

Django: Displaying image from model field?

I'm having trouble getting an image to display. This should be really easy to fix. I'm just a noob. :/
My models.py is the following:
import datetime
from django.db import models
from django.utils import timezone
class Coin(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
ticker = models.CharField(max_length=5)
logo = models.ImageField(upload_to='uploads/', verbose_name='image')
website = models.URLField(max_length=200, default="https://example.com/")
reddit = models.URLField(max_length=200, default="https://reddit.com/r/")
twitter = models.URLField(max_length=200, default="https://twitter.com/")
summary = models.CharField(max_length=500, blank=True)
description = models.TextField()
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.ticker
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class CoinImage(models.Model):
coin = models.ForeignKey(Coin, default=None, related_name='images',
on_delete=models.CASCADE)
image = models.ImageField(upload_to='static/uploads', verbose_name='image')
In my views.py I have:
from django.http import HttpResponse, Http404
from django.template import loader
from django.shortcuts import render
from .models import Coin
def index(request):
latest_coins_list = Coin.objects.order_by('-pub_date')[:5]
context = {'latest_coins_list': latest_coins_list}
return render(request, 'coins/index.html', context)
def detail(request, coin_id):
try:
coin = Coin.objects.get(pk=coin_id)
except Coin.DoesNotExist:
raise Http404("Coin does not exist")
return render(request, 'coins/detail.html', {'coin': coin})
My main urls.py is:
from django.contrib import admin
from django.urls import include, path
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('coins/', include('coins.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My app urls.py is:
from django.urls import path
from django.conf import settings
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<int:coin_id>/', views.detail, name='detail'),
]
Then finally in my template file details.html:
{% load static %}
<img src="{{ coin.logo.path }}" alt="La" />
<h1>{{ coin.name }} | {{ coin.ticker }}</h1>
<p>{{ coin.description }}</p>
<li><strong>Website:</strong> {{ coin.website }}</li>
<li><strong>Twitter:</strong> {{ coin.twitter }}</li>
<li><strong>Reddit:</strong> {{ coin.reddit }}</li>
When I view the template I get the alt text. Then when trying to access the image directly 127.0.0.1:8000/static/uploads/thumbs/me.jpg I get a template error saying:
Page not found (404) Request Method: GET Request URL:
http://127.0.0.1:8000/static/uploads/thumbs/me.jpg Raised by:
django.views.static.serve
'uploads/thumbs/me.jpg' could not be found
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.
This should be a really simple thing to do. If someone can point me in the right direction I would appreciate it so much. Sorry, am noob. :P
Added for someone:
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'i*a%3!kg*mj7j-=5b#_3cx(^%sqr*&sp$-fg*qv=qewm!a-_gt'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'coins',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'blockintel.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'blockintel.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static/')
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
During development, you can serve user-uploaded media files from MEDIA_ROOT. This is te absolute filesystem path to the directory that will hold user-uploaded files. in your settings, you should provide:
# MEDIA_ROOT = os.path.join(BASE_DIR,'your_directory')
MEDIA_ROOT = os.path.join(BASE_DIR,'media') # media most of the time
MEDIA_URL, URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slash if set to a non-empty value. You will need to configure these files to be served in both development and production environments. add this in your settings
# MEDIA_URL = '/your_url/'
MEIDA_URL = '/media/' # most of the time
You will need to do this as well by adding the following snippet to your root urls.py:
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
NOTE: This helper function works only in debug. Know more here
ISSUES / SUGGESTIONS
In this field, rather than uploading a file to static directory, just provide your media directory, in that case, it's media.
image = models.ImageField(upload_to='uploads/', verbose_name='image')
Django will automatically create a directory: 'uploads' inside the MEDIA_ROOT which is media,
So access all your the images that you have with
# file.url
{{ coin.logo.url }}

Categories