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