"Contact Me" form that sends emails to me - python

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

Related

Django contact form not working. GMAIL not recieving message

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

Django contrib message, not printing the Box label

I am new to Django, I built a little app, I want to display a message when I click a button. The message display correctly to the web app but it only show the text, it doesn't show the color box (GREEN FOR SUCCESS, AND RED FOR ERROR). I searched a lot on the DOCS, and stackoverflow but didn't find a answer. Thanks you for helping
views.py
from django.shortcuts import render
from .forms import ClientInfo
from django.contrib import messages
def send_sms(request):
if request.method == 'POST':
form = ClientInfo(request.POST)
if form.is_valid():
try:
sms = Client.messages.create(
from_="+XXXXXXXXXX",
body=mess,
to=sms_client
)
send = sms.sid
messages.add_message(request, messages.SUCCESS, 'Succes! Message has been sent!')
except:
messages.error(request, 'Error! Message has not been sent!')
form.html
{% load crispy_forms_tags %}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
{% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}{% endif %}
{{ message }}
</li>
{% endfor %}
</ul>
{% endif %}
<form method="post">
{% csrf_token %}
{{ form|crispy }}
<br>
<button type="submit">ENVOYER</button>
<br>
</form>
</body>
</html>
settings.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 3.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'zfqh)_o&z_q_=yb)adwq&0gxe-aq4%n4ae8##^=*xyo#gleho6'
# 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',
'polls',
'crispy_forms'
]
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 = 'mysite.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 = 'mysite.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/'
ALLOWED_HOST = ['*']
Ok - I've left some parts out such as importing libraries in python and triggering the ajax request - let me know if you need those. Otherwise if you stick to this pattern you should be able to accomplish a lot with your Django app.
views.py:
# define behavior when requests are sent to 'send_message':
def SendMessage(request):
# unpack request:
status = request.POST['status']
# set message depending on status:
if status == True:
message = 'Everything okay!'
elif status == False:
message = 'Something went wrong...'
# pack context:
context = json.dumps({
'message' : message,
'status' : status,
})
# return an HTTP response with context:
return HttpResponse(context)
urls.py:
# route url to view function:
urlpatterns = [
path('send_message/', views.SendMessage, name='send_message'),
]
template:
// create ajax request:
$.ajax({
// send to url:
url : "{% url 'send_message' %}",
type : 'POST',
// add data to post request:
data : {
'status' : // status is either true or false based on some logic
},
dataType :'json',
// this function executes if we get a succesfull response from the backend:
success : function(context) {
// get the value of 'status' and 'message' that was set in the backend:
var status = context.status
var message = context.message
if (status) {/* do something if status is true */ }
else {/* do something if status is false */}
},
});

LDAP authentication using django

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

Why won't my index.html connect to my index.css file?

My index.html won't connect to my index.css for some reason. I can't see why. Maybe it's the path of files or something. I apologize for such a noob question. My index.css file has a small bit of code just to test out and see if it works.
Here's my index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Page</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
{% load static %}
<link rel="stylesheet" href="{% static 'index.css' %}">
</head>
<body>
<div class="container">
<form method="POST">
{% csrf_token %}
<div class="form-group">
<label for="firstName">First Name:</label>
<input class="form-control" id="firstName" placeholder="Enter first name" name="firstName">
</div>
<div class="form-group">
<label for="">Last Name:</label>
<input class="form-control" id="lastName" placeholder="Enter last name" name="lastName">
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember">Remember me</label></div></br>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</body>
</html>
Here's my index.css file:
html {
background: chocolate;
}
Here's my settings.py file:
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/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '+-9mn+q&u#lw2_=s7&=zin5d7oxbt#v#9jg%2+a7=#noqd_jyf'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'music.apps.MusicConfig',
'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 = 'tyran.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 = 'tyran.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/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/1.11/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/1.11/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.11/howto/static-files/
STATIC_URL = '/static/'
You should load the static files with correct way in Django, better to split static files and templates. Here is one solution based on your case:
Fristly, under music folder, create static folder, put your static file index.css.
After that, change the loading css file with this way in your index.html:
{% load static%}
<link rel="stylesheet" href="{% static 'index.css' %}">
Then, it will load the static file.
Update:
make sure index.css is in the path: tyran/music/static/index.css
Just give it a hard path instead:
<link rel="stylesheet" href="~/music/templates/music/index.css">
Django is looking for a file called "index.css" relative to your project root, not the template directory. See this documentation (https://docs.djangoproject.com/en/1.11/howto/static-files/#serving-static-files-during-development) about setting up a STATIC_URL directory to tell Django where to look for static assets.
There's nothing wrong in the code.
I copied your code and ran on my machine. It works fine.
There's no problem in your code. The connection also is too correct. Try doing it in other IDE or manually.

django avatar custom template directory

I have a new problem with django avatar, can i change template base of django avatar in template custom on my project ?
my current template :
{% extends "templates/base.html" %}
{% load i18n avatar_tags %}
{% block content %}
<p>Your current avatar :</p>
{% avatar user %}
{% if not avatars %}
<p>{% trans "You haven't uploaded an avatar yet. Please upload one now." %}</p>
{% else %}
<form method="POST" action="{% url 'avatar_change' %}">
<ul>
{{ primary_avatar_form.as_ul }}
</ul>
<p>{% csrf_token %}<input type="submit" value="{% trans "Choose new Default" %}" /></p>
</form>
{% endif %}
<form enctype="multipart/form-data" method="POST" action="{% url 'avatar_add' %}">
{{ upload_avatar_form.as_p }}
<p>{% csrf_token %}<input type="submit" value="{% trans "Upload New Image" %}" /></p>
</form>
{% endblock %}
I copy/paste the avatar template directory in my project and the change not work.
EDIT :
My Django version is 1.9.8
Is my settings.py :
""""
# -*- coding: utf-8 -*- """ Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.9.8.
For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """
import os from django.core.mail import send_mail
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# print "base dir path :", BASE_DIR
# resultat du print => /home/cpoudevigne/Projets/MyMemoryBox/mysite
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'fywfd7s#e%36b_g#%!lt3o$t6i5g(&pfa8f9aa5#fhe#%7dzh('
# SECURITY WARNING: don't run with debug turned on in production! DEBUG = True
ALLOWED_HOSTS = []
# Grappelli settings
GRAPPELLI_ADMIN_TITLE = "My Title"
# Application definition
INSTALLED_APPS = [
'grappelli',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'avatar',
'registration',
'mymemoryapp', ]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'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', ]
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/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': 'localhost',
} }
# Django-registration settings ACCOUNT_ACTIVATION_DAYS = 7 LOGIN_REDIRECT_URL = '/'
# Password validation
# https://docs.djangoproject.com/en/1.9/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',
}, ]
# Django-mail Settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' DEFAULT_FROM_EMAIL = ''
# Internationalization
# https://docs.djangoproject.com/en/1.9/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.9/howto/static-files/ PROJECT_DIR = os.path.dirname(__file__) print "PROJECT_DIR :", PROJECT_DIR
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media') MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(PROJECT_DIR, 'mysite', 'static') STATIC_URL
= '/static/'
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(PROJECT_DIR, 'static/'), ) print 'STATICFILES_DIRS :', STATICFILES_DIRS
If you want to override django-avatar's change page, you should place template you present in <appname>/templates/avatar/change.html or <templates_dir>/avatar/change.html if you have configured one.

Categories