Import problem in pycharm with django tutorial - python

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)
]

Related

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.

Images Aren't Loading When Launching Website With Heroku. How Do I Fix This?

when I deploy *my heroku website everything loads up except my The Website Images you could see everything but it shows the images as errors I am not sure how to fix this I been stuck with this problem for almost 2 days if you know how to fix it please explain it to me so in the future I could go back and see this and fix my problem I literally have all the requirements for my website to be launched with heroku but I am not see the images at all
my settings.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 3.1.1.
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/
"""
import os
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 = ''
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False # remember to change to false
ALLOWED_HOSTS = ['anim3-domain.herokuapp.com']
# 'https://anime-domain.herokuapp.com/'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main.apps.MainConfig',
]
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 = 'mysite.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 = 'mysite.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_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
my urls
"""mysite URL Configuration
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("main.url")),
]
my wsgi.py
"""
WSGI config for mysite project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
application = get_wsgi_application()
here is part of the error log
rWarning: No directory at: /app/staticfiles/
2020-10-10T16:21:57.649046+00:00 app[web.1]: warnings.warn(u"No directory at: {}".format(root))
2020-10-10T16:21:57.649987+00:00 app[web.1]: /app/.heroku/python/lib/python3.6/site-packages/whitenoise/base.py:115: UserWarning: No directory at: /app/staticfiles/
2020-10-10T16:21:57.649989+00:00 app[web.1]: warnings.warn(u"No directory at: {}".format(root))
heres the full error log its in pastebin because its to long stack will view it as error
https://pastebin.com/fEr8LQk1

Django Error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/helpdesk/login/?next=/

I'm a beginner. I'm trying to build a helpdesk system using Django helpdesk framework. But when I click on login button, I get the following error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/helpdesk/login/?next=/
Using the URLconf defined in moog.urls, Django tried these URL patterns, in this order:
admin/
^dashboard/$ [name='dashboard']
^tickets/$ [name='list']
^tickets/update/$ [name='mass_update']
^tickets/submit/$ [name='submit']
^tickets/(?P<ticket_id>[0-9]+)/$ [name='view']
^tickets/(?P<ticket_id>[0-9]+)/followup_edit/(?P<followup_id>[0-9]+)/$ [name='followup_edit']
^tickets/(?P<ticket_id>[0-9]+)/followup_delete/(?P<followup_id>[0-9]+)/$ [name='followup_delete']
^tickets/(?P<ticket_id>[0-9]+)/edit/$ [name='edit']
^tickets/(?P<ticket_id>[0-9]+)/update/$ [name='update']
^tickets/(?P<ticket_id>[0-9]+)/delete/$ [name='delete']
^tickets/(?P<ticket_id>[0-9]+)/hold/$ [name='hold']
^tickets/(?P<ticket_id>[0-9]+)/unhold/$ [name='unhold']
^tickets/(?P<ticket_id>[0-9]+)/cc/$ [name='ticket_cc']
^tickets/(?P<ticket_id>[0-9]+)/cc/add/$ [name='ticket_cc_add']
^tickets/(?P<ticket_id>[0-9]+)/cc/delete/(?P<cc_id>[0-9]+)/$ [name='ticket_cc_del']
^tickets/(?P<ticket_id>[0-9]+)/dependency/add/$ [name='ticket_dependency_add']
^tickets/(?P<ticket_id>[0-9]+)/dependency/delete/(?P<dependency_id>[0-9]+)/$ [name='ticket_dependency_del']
^tickets/(?P<ticket_id>[0-9]+)/attachment_delete/(?P<attachment_id>[0-9]+)/$ [name='attachment_del']
^raw/(?P<type>\w+)/$ [name='raw']
^rss/$ [name='rss_index']
^reports/$ [name='report_index']
^reports/(?P<report>\w+)/$ [name='run_report']
^save_query/$ [name='savequery']
^delete_query/(?P<id>[0-9]+)/$ [name='delete_query']
^settings/$ [name='user_settings']
^ignore/$ [name='email_ignore']
^ignore/add/$ [name='email_ignore_add']
^ignore/delete/(?P<id>[0-9]+)/$ [name='email_ignore_del']
^$ [name='home']
^view/$ [name='public_view']
^change_language/$ [name='public_change_language']
^rss/user/(?P<user_name>[^/]+)/$ [name='rss_user']
^rss/user/(?P<user_name>[^/]+)/(?P<queue_slug>[A-Za-z0-9_-]+)/$ [name='rss_user_queue']
^rss/queue/(?P<queue_slug>[A-Za-z0-9_-]+)/$ [name='rss_queue']
^rss/unassigned/$ [name='rss_unassigned']
^rss/recent_activity/$ [name='rss_activity']
^login/$ [name='login']
^logout/$ [name='logout']
^password_change/$ [name='password_change']
^password_change/done$ [name='password_change_done']
^kb/$ [name='kb_index']
^kb/(?P<item>[0-9]+)/$ [name='kb_item']
^kb/(?P<item>[0-9]+)/vote/$ [name='kb_vote']
^kb/(?P<slug>[A-Za-z0-9_-]+)/$ [name='kb_category']
^help/context/$ [name='help_context']
^system_settings/$ [name='system_settings']
The current path, helpdesk/login/, didn't match any of these.
Below is my settings.py :
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 = '7)%lt=ea(z6mi1k$3ho5jmlz^(5kz01h78&f6pl7u=k6$1hzao'
# 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',
'django.contrib.sites',
'django.contrib.humanize',
'markdown_deux',
'bootstrapform',
'helpdesk',
'moog',
]
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 = 'moog.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 = 'moog.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
SITE_ID = 1
LOGIN_REDIRECT_URL = '/helpdesk/login/'
LOGIN_URL = '/helpdesk/login/'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_ROOT = 'Users/mahes/Dev/moog/django-helpdesk-master/helpdesk/static/helpdesk'
STATIC_URL = '/static/'
urls.py:
"""moog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/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
from django.conf.urls import include,url
urlpatterns = [
path(r'admin/', admin.site.urls),
path(r'', include('helpdesk.urls')),
#url(r'', include('mail.urls'))
]
Adding Urls.py from helpdesk sitepackage:
"""
django-helpdesk - A Django powered ticket tracker for small enterprise.
(c) Copyright 2008 Jutda. All Rights Reserved. See LICENSE for details.
urls.py - Mapping of URL's to our various views. Note we always used NAMED
views for simplicity in linking later on.
"""
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from django.contrib.auth import views as auth_views
from django.views.generic import TemplateView
from helpdesk import settings as helpdesk_settings
from helpdesk.views import feeds, staff, public, kb, login
class DirectTemplateView(TemplateView):
extra_context = None
def get_context_data(self, **kwargs):
context = super(self.__class__, self).get_context_data(**kwargs)
if self.extra_context is not None:
for key, value in self.extra_context.items():
if callable(value):
context[key] = value()
else:
context[key] = value
return context
app_name = 'helpdesk'
urlpatterns = [
url(r'^dashboard/$',
staff.dashboard,
name='dashboard'),
url(r'^tickets/$',
staff.ticket_list,
name='list'),
url(r'^tickets/update/$',
staff.mass_update,
name='mass_update'),
url(r'^tickets/submit/$',
staff.create_ticket,
name='submit'),
url(r'^tickets/(?P<ticket_id>[0-9]+)/$',
staff.view_ticket,
name='view'),
url(r'^tickets/(?P<ticket_id>[0-9]+)/followup_edit/(?P<followup_id>[0-9]+)/$',
staff.followup_edit,
name='followup_edit'),
url(r'^tickets/(?P<ticket_id>[0-9]+)/followup_delete/(?P<followup_id>[0-9]+)/$',
staff.followup_delete,
name='followup_delete'),
url(r'^tickets/(?P<ticket_id>[0-9]+)/edit/$',
staff.edit_ticket,
name='edit'),
url(r'^tickets/(?P<ticket_id>[0-9]+)/update/$',
staff.update_ticket,
name='update'),
url(r'^tickets/(?P<ticket_id>[0-9]+)/delete/$',
staff.delete_ticket,
name='delete'),
url(r'^tickets/(?P<ticket_id>[0-9]+)/hold/$',
staff.hold_ticket,
name='hold'),
url(r'^tickets/(?P<ticket_id>[0-9]+)/unhold/$',
staff.unhold_ticket,
name='unhold'),
url(r'^tickets/(?P<ticket_id>[0-9]+)/cc/$',
staff.ticket_cc,
name='ticket_cc'),
url(r'^tickets/(?P<ticket_id>[0-9]+)/cc/add/$',
staff.ticket_cc_add,
name='ticket_cc_add'),
url(r'^tickets/(?P<ticket_id>[0-9]+)/cc/delete/(?P<cc_id>[0-9]+)/$',
staff.ticket_cc_del,
name='ticket_cc_del'),
url(r'^tickets/(?P<ticket_id>[0-9]+)/dependency/add/$',
staff.ticket_dependency_add,
name='ticket_dependency_add'),
url(r'^tickets/(?P<ticket_id>[0-9]+)/dependency/delete/(?P<dependency_id>[0-9]+)/$',
staff.ticket_dependency_del,
name='ticket_dependency_del'),
url(r'^tickets/(?P<ticket_id>[0-9]+)/attachment_delete/(?P<attachment_id>[0-9]+)/$',
staff.attachment_del,
name='attachment_del'),
url(r'^raw/(?P<type>\w+)/$',
staff.raw_details,
name='raw'),
url(r'^rss/$',
staff.rss_list,
name='rss_index'),
url(r'^reports/$',
staff.report_index,
name='report_index'),
url(r'^reports/(?P<report>\w+)/$',
staff.run_report,
name='run_report'),
url(r'^save_query/$',
staff.save_query,
name='savequery'),
url(r'^delete_query/(?P<id>[0-9]+)/$',
staff.delete_saved_query,
name='delete_query'),
url(r'^settings/$',
staff.user_settings,
name='user_settings'),
url(r'^ignore/$',
staff.email_ignore,
name='email_ignore'),
url(r'^ignore/add/$',
staff.email_ignore_add,
name='email_ignore_add'),
url(r'^ignore/delete/(?P<id>[0-9]+)/$',
staff.email_ignore_del,
name='email_ignore_del'),
]
urlpatterns += [
url(r'^$',
public.homepage,
name='home'),
url(r'^view/$',
public.view_ticket,
name='public_view'),
url(r'^change_language/$',
public.change_language,
name='public_change_language'),
]
urlpatterns += [
url(r'^rss/user/(?P<user_name>[^/]+)/$',
login_required(feeds.OpenTicketsByUser()),
name='rss_user'),
url(r'^rss/user/(?P<user_name>[^/]+)/(?P<queue_slug>[A-Za-z0-9_-]+)/$',
login_required(feeds.OpenTicketsByUser()),
name='rss_user_queue'),
url(r'^rss/queue/(?P<queue_slug>[A-Za-z0-9_-]+)/$',
login_required(feeds.OpenTicketsByQueue()),
name='rss_queue'),
url(r'^rss/unassigned/$',
login_required(feeds.UnassignedTickets()),
name='rss_unassigned'),
url(r'^rss/recent_activity/$',
login_required(feeds.RecentFollowUps()),
name='rss_activity'),
]
urlpatterns += [
url(r'^login/$',
login.login,
name='login'),
url(r'^logout/$',
auth_views.LogoutView.as_view(
template_name='helpdesk/registration/login.html',
next_page='../'),
name='logout'),
url(r'^password_change/$',
auth_views.PasswordChangeView.as_view(
template_name='helpdesk/registration/change_password.html',
success_url='./done'),
name='password_change'),
url(r'^password_change/done$',
auth_views.PasswordChangeDoneView.as_view(
template_name='helpdesk/registration/change_password_done.html',),
name='password_change_done'),
]
if helpdesk_settings.HELPDESK_KB_ENABLED:
urlpatterns += [
url(r'^kb/$',
kb.index,
name='kb_index'),
url(r'^kb/(?P<item>[0-9]+)/$',
kb.item,
name='kb_item'),
url(r'^kb/(?P<item>[0-9]+)/vote/$',
kb.vote,
name='kb_vote'),
url(r'^kb/(?P<slug>[A-Za-z0-9_-]+)/$',
kb.category,
name='kb_category'),
]
urlpatterns += [
url(r'^help/context/$',
TemplateView.as_view(template_name='helpdesk/help_context.html'),
name='help_context'),
url(r'^system_settings/$',
DirectTemplateView.as_view(template_name='helpdesk/system_settings.html'),
name='system_settings'),
]
Please help me how to debug this and fix this
Thanks in Advance.
As the log showed
^login/$ [name='login']
^logout/$ [name='logout']
The login URL should be http://127.0.0.1:8000/login but you accessed http://127.0.0.1:8000/helpdesk/login
Either edit your frontend path that point to /login (without /helpdesk) or
# inside urls.py
path(r'helpdesk/', include('helpdesk.urls')),
Change your settings as follows
LOGIN_REDIRECT_URL = '/login/'
LOGIN_URL = '/login/'
Similar to bmons' solution, I added the following code (without LOGIN_URL = '/login/') to the top (or bottom) of my project's settings.py:
# My settings
LOGIN_URL = '/login/'
We do not need to specify the 'users' sub-directory when writing URLs in a Django v3.0 Project's settings.

getting error 404 in django framework python

I am newbie in django and I try to build webapp by using django framework to upload image and show on web page.
After somehow solving many errors form urls.py finally server run but at last again Page not found (404) error on web page.
i upload all necessary code below.
myproject/myproject/settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '2z$tk#wj&&pc(0ps4!7w_o_lm4h!3flwy+8%%s3k5pqars=ta&'
# 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',
'myapp', )
MIDDLEWARE_CLASSES = (
'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 = 'myproject.urls'
WSGI_APPLICATION = 'myproject.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': os.path.join(PROJECT_ROOT, 'database/database.sqlite3'), # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
'''
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
'''
# Internationalization
# https://docs.djangoproject.com/en/1.6/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/1.6/howto/static-files/
STATIC_URL = '/static/'
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home2/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
#trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
myproject/myapp/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.list, name='list'),
url(r'^$', views.index, name='index'),
url(r'^list/$', views.list, name='list'),
]
myproject/myapp/views.py
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from myapp.models import Document
from myapp.forms import DocumentForm
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('list'))
else:
form = DocumentForm() # A empty, unbound form
#Load documents for the list page
documents = Document.objects.all()
#Render list page with the documents and the form
return render_to_response(
'myapp/list.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
def index(request):
return render_to_response('myapp/index.html')
myproject/myproject/urls.py
from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import RedirectView
from django.contrib import admin
# admin.autodiscover()
urlpatterns = [
url(r'^myapp/', include('myapp.urls')),
url(r'^admin/', include(admin.site.urls)),
]
urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
myproject/myapp/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
# url(r'^$', views.list, name='list'),
url(r'^$', views.index, name='index'),
url(r'^list/$', views.list, name='list'),
]
terminal screenshot
updated error
Your URLs are currently set up for:
127.0.0.1:8000/myapp/
127.0.0.1:8000/myapp/list/
127.0.0.1:8000/admin
127.0.0.1:8000/ doesn't have a URL set up - based on this SO answer you can create an index page like so:
from django.views.generic.base import TemplateView
urlpatterns = [
url(r'^myapp/', include('myapp.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', TemplateView.as_view(template_name='myapp/index.html'),
name='home'),
]
or just direct your browser to one of those URLs first listed.
Update: Looks like you're also missing your Templates settings, add the following to your settings.py if it's not currently there.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'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',
],
},
},
]
Django URLs can be a bit tricky to get the hang of - you may want to read the documentation on them

Django Markdown Editor does not show up

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}}

Categories