Could anyone of you please help me to implement LDAP authentication using Django. I want to develop a web application which should allow users to access the application post LDAP authentication. I have coded the basic things but I get some failures.
Settings.py
"""
Django settings for HandBook project.
Generated by 'django-admin startproject' using Django 2.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
import ldap
from django_auth_ldap.config import LDAPSearch
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
AUTH_LDAP_SERVER_URI = "serverIp"
AUTHENTICATION_BACKENDS = ('django_auth_ldap.backend.LDAPBackend')
AUTH_LDAP_CONNECTION_OPTIONS = {
ldap.OPT_REFERRALS: 0
}
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '4xkkb*m!&#^xzhkpe6#gxe#xeee0ug3q0h$#-)#lv8+0dqpid*'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ["192.168.113.75"]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'NewHandBook.apps.NewhandbookConfig',
]
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',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
]
ROOT_URLCONF = 'HandBook.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, '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 = 'HandBook.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/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.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/2.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/2.1/howto/static-files/
STATIC_URL = '/static/'
Views.py
from django.shortcuts import render
from django.contrib.auth import authenticate, login
from django.template import RequestContext
from django.shortcuts import render_to_response
def login(request):
return render(request, 'login/login.html')
def login_user(request):
username = password = ""
state = ""
if request.POST:
username = request.POST.get('username')
password = request.POST.get('password')
print(username, password)
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return render(request, 'login/base.html', {'state': state, 'username': username})
else:
return render(request, 'login/login.html', {'state': state, 'username': username})
)
login.html
{% extends 'login/base.html' %}
{% load static %}
<html>
<head>
<title>Login</title>
</head>
<body>
{% block body %}
<form method="post" action="/NewHandBook/validate/">{% csrf_token %}
<div class="container">
<div class="row">
<div class="col-md-10 offset=md-1">
<div class="row">
<div class="col-md-5 register-left "><br><br>
<img style="width: 350px;position: absolute;margin-left: -350px;margin-top: -80px"
src="{% static 'images/gar.png' %}">
<h1 style="font-family: Brush Script MT;font-size: 70px;margin-top: 45px;margin-left: -342px">
HandBook.</h1>
<p style="font-family: Courier New;margin-top: -20px;margin-left: -359px "><i
class="fas fa-shield-alt"></i> Secure <i
class="far fa-share-square"></i> Share <i class="far fa-smile-beam"></i> Smile
</p>
</div>
<div class="col-md-7 register-right">
<h2 style="font-family: Courier;color: azure">Login Here</h2>
<h7 style="font-family: Courier;font-size: 13px;color: aliceblue">
<h7 style="color: red">*</h7>
Please use your system credentials
</h7>
<div class="register-form">
<div class="form-group">
<input type="text" name="username" class="form-control" placeholder="User name"
style="font-family: Courier">
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" placeholder="Password"
style="font-family: Courier">
</div>
<input type="reset" class="btn btn-primary" value="Reset">
<button type="submit" class="btn btn-primary"> Login Now</button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
{% endblock %}
</body>enter code here
</html>## Heading ##
I get below error when i run my project
exception
Could anyone of you please help me here.
My use case:
user should be able to land on some home page after a successful login or should land back on same login page if provided credentials are invalid.
The error indicates that you are passing a single Python path where you should actually pass a list of Python paths, i.e. django.some.module.path instead of ['django.some.module.path']
Django then iterates over the string, and tries to import each character. In case of django.some.module.path, Django tries to import d, which gives you the error you are seeing.
To pinpoint the exact source of the error, you have to provide the complete traceback. You can click on 'Switch to copy-and-paste view' on the Debug Error page.
Update:
Here is your error:
AUTHENTICATION_BACKENDS = ('django_auth_ldap.backend.LDAPBackend')
Single entry tuples need a comma, like this:
AUTHENTICATION_BACKENDS = ('django_auth_ldap.backend.LDAPBackend',)
Start using the default LoginView
def login(request):
return LoginView.as_view(template_name='login.html')(request)
This shall work. If it does now implement your customized login method in a LoginView class...
Related
I don't know why this problem is occuring. The login page is being rendered fine. But when I am clicking the Log In button after filling out the forms, I am getting this error. Can anyone help me solve this?
My settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = True
ALLOWED_HOSTS = []
import sys
sys.modules['fontawesome_free'] = __import__('fontawesome-free')
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'class2.apps.Class2Config',
'crispy_forms',
'django_bootstrap_icons',
'fontawesome_free',
]
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 = 'abrar_class.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 = 'abrar_class.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/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
LOGIN_REDIRECT_URL = ""
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
My urls.py:
from django import VERSION
from django.urls import path
from django.contrib.auth import views as auth_views
from .views import CourseDetailView, CourseListView, YourCourses, ProfileDetailView
from . import views
urlpatterns = [
path("", CourseListView.as_view(), name="index"),
path("login/", auth_views.LoginView.as_view(template_name='class/login.html'), name='login'),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("<slug>", CourseDetailView.as_view(), name="course"),
path('get_enrolled/<slug>/', views.get_enrolled, name='get_enrolled'),
path('your_courses/', YourCourses.as_view(), name='your_courses'),
path('profile/<int:pk>/', ProfileDetailView.as_view(), name='profile'),
]
My login.html file:
{% extends "class/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<br>
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group" style="color: #f5a425">
<legend class="border-bottom mb-4" style="color:#f5a425;">Log In</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-warning" type="submit">Login</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Need An Account? <a class="ml-2" href="{% url 'register' %}">Sign Up</a>
</small>
</div>
</div>
{% endblock content %}
You've specified LOGIN_REDIRECT_URL = "". The documentation for this setting says:
The URL or named URL
pattern
where requests are redirected after login when the
LoginView
doesn’t get a next GET parameter.
This means what is happening is that Django is assuming you to have specified a url name instead of a url. You can instead set the setting as follows if you want to redirect to the home page:
LOGIN_REDIRECT_URL = "/"
Or you can actually use the url name:
LOGIN_REDIRECT_URL = "index"
I have the following HTML page:
{% load static %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Contact Me</title>
<link rel="stylesheet" href="{% static 'projects/style_contact.css' %}">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="container">
<div class="text">Contact Me</div>
<form method="POST">
{% csrf_token %}
<div class="form-row">
<div class="input-data">
<div class="underline"></div>
<input type="text" name="name" required placeholder="Name">
</div>
<div class="input-data">
<div class="underline"></div>
<input type="text" name="email" required placeholder="Email Address">
</div>
</div>
<div class="form-row">
<div class="input-data">
<div class="underline"></div>
<input type="password" name="password"required placeholder="Password">
</div>
</div>
<div class="form-row">
<div class="input-data textarea">
<div class="underline"></div>
<input type="text" name="message" required placeholder="Write your message">
</div>
</div>
<div class="form-row submit-btn">
<div class="input-data">
<div class="inner"></div>
<input type="submit" value="submit">
</div>
</div>
</form>
</div>
</body>
</html>
I want to be able to send emails from that form. I know that all the Email configurations need to go inside the settings.py file, but how would i make sure that the legitimate owner of that email sends the message.
The form needs to get the correct password of that specific email address so that the legitimate owner is the only one who can actually send the message.
Any ideas??
Here is what i mean:
my email address is nn#nn.com (not really). I have a password too. My friends email address is n2#nn.com (no really). I do not have the password to that. How would i prevent me from sending an email through the Django form using my friends email. Because that is a security problem. Any ideas??
The settings.py file is:
"""
Django settings for src project.
Generated by 'django-admin startproject' using Django 4.0.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent #this was the original
# 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/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-1!2hpx5ba$=lnvq#zu_98shz6#tj&uf#u0#pxh&tu+nm+l%5wr'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
#Email Stuff
EMAIL_HOST = 'smtp.zoho.com'
EMAIL_HOST_USER = '' # This is the 'from'
EMAIL_HOST_PASSWORD = '' # This is the password of the 'from'
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'projects',
]
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 = 'src.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 = 'src.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Email settings
EMAIL_HOST = 'localhost'
EMAIL_PORT = 1025
EMAIL_HOST_USER = ""
EMAIL_HOST_PASSWORD = ""
EMAIL_USE_TLS = False
# EMAIL_USE_SSL = False
I guess my question is: Can i put the email configs in the views file?
change this
# Email settings
EMAIL_HOST = 'localhost'
EMAIL_PORT = 1025
EMAIL_HOST_USER = ""
EMAIL_HOST_PASSWORD = ""
EMAIL_USE_TLS = False
# EMAIL_USE_SSL = False
Add this instead
EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = 'from#gmail.com' # this email will be used to send emails
EMAIL_HOST_PASSWORD = 'xyz' # host email password required
# now sign in with your host gmail account in your browser
# open following link and turn it ON
# https://myaccount.google.com/lesssecureapps
# otherwise you will get SMTPAuthenticationError at /contactus
# this process is required because google blocks apps authentication by default
EMAIL_RECEIVING_USER = ['to#gmail.com'] # email on which you will receive messages sent from website
Hey guys sorry to bother you, I'm new to django and I made a personal portfolio and locally everything is perfect but the deployed one is not loading the images that I upload on the live app.
I tried to see youtube videos a lot of topics over here and I cant find a solution...:(
Heres my code:
settings.py
import os
import django_heroku
from decouple import config
import dj_database_url
# 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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['***********']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'portfolio',
]
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 = 'my_portfolio.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 = 'my_portfolio.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.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/3.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/3.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/3.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_TMP = os.path.join(BASE_DIR, 'static')
os.makedirs(STATIC_TMP, exist_ok=True)
os.makedirs(STATIC_ROOT, exist_ok=True)
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
django_heroku.settings(locals())
urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from portfolio import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
models.py
from django.db import models
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.CharField(max_length=250)
image = models.ImageField(upload_to='portfolio/images')
url = models.URLField(blank=True)
def __str__(self):
return self.title
home.html
{% extends "portfolio/base.html" %}
{% load static %}
{% block content %}
<div class="row justify-content-center my-3">
<div class="col-5">
<img src="{% static 'portfolio/pic_me.jpg' %}" class="img-fluid">
</div>
</div>
<div class="row justify-content-center mb-3">
<div class="col-md-9 text-center">
<h1 id="hometext" class="font-weight-bold">Hello</h1>
</div>
</div>
<h2 class="mt-5">Portfolio</h2>
<hr>
<div class="row">
{% for project in projects %}
<div class="col-lg-4 col-md-6">
{% if project.url %}
<a href="{{ project.url }}">
<img src="{{ project.image.url }}" class="img-fluid mb-2">
</a>
{% else %}
<img src="{{ project.image.url }}" class="img-fluid mb-2">
{% endif %}
<div class="textport">
<h3>{{ project.title }}</h3>
<p>{{ project.description }}</p>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
Serving media and static files by django in live server and prod is discouraged from the developer themselves, it only should be used when in debug mode.
As for your bug, did you try accessing /media/portfolio/images/uploaded_image and see if it shows an uploaded image ?
Also verify the path of your static folder my_app/static/my_app/example.jpg
The doc may help: https://docs.djangoproject.com/en/2.2/howto/static-files/
I am trying to use a simple contact form using Gmail configuration.
When users click sends message button it reloads to should reload to the home page and should send messages to hosted email.
I don't get any email with this process. I don't understand where I am going wrong.
Forms.html
{% extends 'base.html' %}
{% block content %}
<form action="{% url 'home' %}" method="post" id="contactForm" name="sentMessage" novalidate="novalidate">
<!-- -->
{% csrf_token %}
<div class="row align-items-stretch mb-5">
<div class="col-md-6">
<div class="form-group">
<input class="form-control" id="name" type="text" name="message_name" placeholder="Your Name *" required="required" data-validation-required-message="Please enter your name." />
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input class="form-control" id="email" type="email" name="message_email" placeholder="Your Email *" required="required" data-validation-required-message="Please enter your email address." />
<p class="help-block text-danger"></p>
</div>
<div class="form-group mb-md-0">
<input class="form-control" id="phone" type="tel" name="message_phone" placeholder="Your Phone *" required="required"/>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="col-md-6">
<div class="form-group form-group-textarea mb-md-0">
<textarea class="form-control" id="message" name="message_text" placeholder="Your Message *" required="required" data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
</div>
<div class="text-center form-group">
<div id="success"></div>
<button class="btn btn-primary btn-xl text-uppercase" id="sendMessageButton" type="submit">Send Message</button>
</div>
</form>
{% endblock content %}
view.py File
from django.shortcuts import render
from django.conf import settings
from django.core.mail import send_mail
# Create your views here.
def home(request):
return render(request, 'resumesite/forms.html', {})
def form(request):
if request.method == "POST":
message_name = request.POST('message_name')
message_email = request.POST('message_email')
message_phone = request.POST('message_phone')
message_text = request.POST('message_text')
send_mail(
'message_name', #subject
'message_text', #message
'message_email', #from_email
['chaitu.orakala#gmail.com'],#to_email
)
return render(request, 'resumesite/forms.html', {'message_name': message_name})
else:
return render(request, 'resumesite/forms.html', {})
settings.py file
import os
import django_heroku
from decouple import config
import dj_database_url
# 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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'm*8e65ela2^)hdb-yl&j!%_!e8p*)+_%1(l&a#jw6rwlds17o*'
# 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',
'resumesite',
]
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 = 'djangoresume.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, '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 = 'djangoresume.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.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/3.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/3.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/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
django_heroku.settings(locals())
# Email config
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'privacy reasons too7k it off'
EMAIL_HOST_PASSWORD = 'privacy reasons took off'
EMAIL_USE_TLS = True
Project Tree
Try sending dummy email with django shell if not successful edit the email config as below
Try modifying # Email config
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'privacy reasons too7k it off'
EMAIL_HOST_PASSWORD = 'privacy reasons took off'
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'youremail#gmail.com'
SERVER_EMAIL = 'youremail#gmail.com'
def form(request):
if request.method == "POST":
message_name = request.POST('message_name')
message_email = request.POST('message_email')
message_phone = request.POST('message_phone')
message_text = request.POST('message_text')
Changed to code to following then it worked.
def form(request):
if request.method == "POST":
message_name = request.POST['message_name']
message_email = request.POST['message_email']
message_phone = request.POST['message_phone']
message_text = request.POST['message_text']
I am working on the login/logout functionality of a basic Django website. (CS50's Pinocchio's Pizza). The logout path is being injected into the URL & I am unsure as to why. My navbar links to the home page, yet when I click on it it redirects me to the logout page. Any other link I click, that link's path is added to the URL but attached to the logout path.
For example, clicking on the login button of my site, whose path is login_default, the url becomes:
http://127.0.0.1:8000/logoutlogin_default
Trying to click the link in the navbar that should link to the index page gets me:
http://127.0.0.1:8000/logout
The folder "orders" is an app which "pizza" is made aware of. All html pages are inside orders/templates/orders.
This is orders/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name = "index"),
path("register_default", views.register_default, name = "register_default"),
path("register_setup", views.register_setup, name = "register"),
path("login_default", views.login_default, name = "login_default"),
path("login_setup", views.login_setup, name = "login"),
path("logout", views.logout_view, name="logout"),
]
In pizza/urls.py, the Orders app's URLs have been made known:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("", include("orders.urls")),
path("register_default", include("orders.urls")),
path("register_setup", include("orders.urls")),
path("login_default", include("orders.urls")),
path("login_setup", include("orders.urls")),
path("logout", include("orders.urls")),
path("admin/", admin.site.urls),
]
This is orders/views.py
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
# Create your views here.
def index(request):
# If user is not logged in
if not request.user.is_authenticated:
return render(request, "orders/index.html", {"message": None})
context = {
"user": request.user
}
return render(request, "orders/index.html", context)
def register_default(request):
return render(request, "orders/register.html")
def register_setup(request):
firstName = request.POST["userFirstName"]
lastName = request.POST["userLastName"]
email = request.POST["userEmail"]
pw = request.POST["userPW"]
user = User.objects.create_user(firstName, email, pw)
user.save()
return HttpResponseRedirect(reverse("index"))
def login_default(request):
return render(request, "orders/login.html")
def login_setup(request):
username = request.POST["loginName"]
password = request.POST["loginPW"]
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "orders/login.html", {"message": "Invalid Credentials"})
def logout_view(request):
logout(request)
return render(request, "orders/login.html", {"message": "Logged Out"})
This is base.html, which all other templates are based off of.
<!DOCTYPE html>
<html lang="en">
<head>
{% block head %}{% endblock %}
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<nav class="navbar navbar-expand-md bg-light">
Pinocchio's Pizza
<ul class="navbar-nav">
{% if message %}
<li class="nav-item">
Log Out
</li>
{% else %}
<li class="nav-item">
Log In
</li>
<li class="nav-item">
Sign Up
</li>
{% endif %}
</ul>
</nav>
{% block body %}{% endblock %}
</body>
</html>
This is login.html
{% extends "orders/base.html" %}
{% block title %}Log In{% endblock %}
{% block body %}
{% if message %}
<h1 class="text-danger">{{ message }}</h1>
{% endif %}
<div class="container-fluid">
<div class="row">
<div class="col-md-6 mx-auto mt-4">
<form action="{% url 'login' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="loginName">First Name</label>
<input type="text" name="loginName" id="loginName" class="form-control">
</div>
<div class="form-group">
<label for="loginPW">Password</label>
<input type="password" class="form-control" name="loginPW" id="loginPW">
</div>
<button class="btn btn-success" type="submit">Log In</button>
</form>
</div>
</div>
</div>
{% endblock %}
This is pizza/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.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'i0&iq&e9u9h6(4_7%pt2s9)f=c$kso=k$c$w#fi9215s=1q0^d'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'orders.apps.OrdersConfig',
'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 = 'pizza.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 = 'pizza.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/'
Try changing pizza/urls.pyto the following:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("", include("orders.urls")),
path("admin/", admin.site.urls),
]
the reason is the "" path should automatically include all the urls in orders.urls. Here is a link to the documentation: https://docs.djangoproject.com/en/2.2/topics/http/urls/#including-other-urlconfs
Another thing that I noticed that helps catch bugs is to include a / at the end of urls so in your orders/urls.py you can change it to the following.
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name = "index"),
path("register_default/", views.register_default, name = "register_default"),
path("register_setup/", views.register_setup, name = "register"),
path("login_default/", views.login_default, name = "login_default"),
path("login_setup/", views.login_setup, name = "login"),
path("logout/", views.logout_view, name="logout"),
]