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

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.

Related

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 Login Required Middleware does not redirect

I'm super new to Django and I have created a middleware that should direct my users to the index page with login view when trying to access the pages that are supposed to work only for logged users. Even though I don't get any error in my terminal, it does not work. When I type http://127.0.0.1:8000/profile/ in my browser, I'm still able to see it. Instead of that, I would like to direct my users to the login page.
movie_project/middleware.py
from django.http import HttpResponseRedirect
from django.conf import settings
from re import compile
EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]
class LoginRequiredMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
return self.get_response(request)
def process_request(self, request):
assert hasattr(request, 'user')
if not request.user.is_authenticated():
path = request.path_info.lstrip('/')
if not any(m.match(path) for m in EXEMPT_URLS):
return HttpResponseRedirect(settings.LOGIN_URL)
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = ''
DEBUG = True
ALLOWED_HOSTS = []
SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))
# Application definition
INSTALLED_APPS = [
'movies_app',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'multiselectfield'
]
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',
'movie_project.middleware.LoginRequiredMiddleware',
]
LOGIN_URL = 'movies_app.views.index'
LOGIN_URL = '/index/'
MIDDLEWARE_CLASSES = (
'python.path.to.LoginRequiredMiddleware',
)
ROOT_URLCONF = 'movie_project.urls'
AUTH_USER_MODEL = 'movies_app.User'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
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',
'django.template.context_processors.media',
],
},
},
]
TEMPLATE_DIRS = (
os.path.join(SETTINGS_PATH, 'templates'),
)
WSGI_APPLICATION = 'movie_project.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
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',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
urls.py
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from .views import editprofile
from . import views
app_name = 'movies_app'
urlpatterns = [
path('', views.login, name='login'),
path('browse/', views.index, name='index'),
path('register/', views.register, name='register'),
path('movies/', views.allMovies, name='allMovies'),
path('movies/<int:pk>/', views.movie, name='movie'),
path('movies/<int:pk>/rate', views.addRating, name='rate'),
path('my-list/', views.myMovies, name='my-list'),
path('my-list/<int:pk>/delete', views.deleteFavoriteMovie, name='favorite-movie-delete'),
path('profile/', views.profile, name='register'),
path('editprofile/', views.editprofile, name='editprofile'),
path('logout/', views.logout, name='logout'),
path('movie-video', views.movieVideo, name='movie-video')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Anyone knows where can be a problem? Thank you so much for any help!
Your login required middleware does not appear to be doing anything outside of the normal. Is there a reason you have not simply used the login_required decorator on some of your views?
This decorator can be added to any (class based or function based) view where authentication is required. For example
from django.contrib.auth.decorators import login_required
#login_required
def movies_list(request):
...
This will then automatically render the view for all users who are logged in and otherwise redirect the user to the LOGIN_URL if not authenticated.
Whilst you can run your own middleware for such auth, I would strongly use the battle-tested options within the Django framework.
In the case of your comment above:
When I type http://127.0.0.1:8000/profile/ in my browser, I'm still able to see it. Instead of that, I would like to direct my users to the login page.
On your profile view function or class base method simply add #login_required with the appropriate import statement (from django.contrib.auth.decorators import login_required).
It's somewhat confusing to have two variables named the same thing in settings.py?
LOGIN_URL = 'movies_app.views.index'
LOGIN_URL = '/index/'
They're just above MIDDLEWARE_CLASSES. Here' a reference to the HTTPResponseRedirect. https://docs.djangoproject.com/en/3.0/ref/request-response/#django.http.HttpResponseRedirect In other words, delete the one that says movies_app.views.index

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.

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

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

Categories