Django contrib message, not printing the Box label - python

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 */}
},
});

Related

why i am getting the error 'temp1app.CustomUser.user_pe rmissions' or 'auth.User.user_permissions'?

Hope you are doing well, i am beginner to the django and python, encountered the error while practicing projects from the github which is the user authentication project. i have posted a code below. feel free to ask if you have any questions. i have
posted a question in this StackOverflow website
to find the solution for the issue. please solve
the issue. Thanks a lot for your help.
python manage.py migrate
Traceback (most recent call last):
File
"C:\Users\Dhani\anaconda3\
envs\myDjangoEnv\lib\site-
packages\django\db\migrations\loader.py", l
ine 187, in check_key
return self.graph.root_nodes(key[0])[0]
IndexError: list index out of range
During handling of the above exception, another
exception occurred:
Traceback (most recent call last):
File "E:\Programming1\GitHub\
1\temp1\manage.py", line 22, in <module>
main()
File "E:\Programming1\GitHub\1\temp1\manage.py",
line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\Dhani\anaconda3\
envs\myDjangoEnv\lib\site-
packages\django\
core\management\__init__.py
", line 446, in execute_from_command_line
utility.execute()
File "C:\Users\Dhani\anaconda3\
envs\myDjangoEnv\lib\site-packages\django\core\
management\__init__.py
", line 440, in execute
self.fetch_command(subcommand).
run_from_argv(self.argv)
File "C:\Users\Dhani\anaconda3\envs\
myDjangoEnv\lib\site-packages\django\core\
management\base.py", l
ine 414, in run_from_argvself.execute
(*args, **cmd_options)
File "C:\Users\Dhani\anaconda3\
envs\myDjangoEnv\lib\site-packages\django\core\
management\base.py", l
ine 460, in execute
output = self.handle(*args, **options)
ine 250, in build_graph
self.add_external_dependencies(key, migration)
File "C:\Users\Dhani\anaconda3\
envs\myDjangoEnv\lib\site-packages\
django\db\migrations\loader.py", l
ine 214, in add_external_dependencies
parent = self.check_key(parent, key[0])
File
"C:\Users\Dhani\anaconda3\envs
\myDjangoEnv\lib\site-
packages\django\db\migrations\loader.py", l
ine 194, in check_key
raise ValueError(
ValueError: Dependency on app with no migrations:
temp1app
temp1/settings.py
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR=os.path.join(BASE_DIR,'templates')
# 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-fzd#
(ie_srm3k^c+ggwzh5e$gu3j+dp#%!yg92r87r&61d16zr'
# 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',
'temp1app',
]
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 = 'temp1.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATES_DIR,],
'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 = 'temp1.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/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-
field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
#AUTH_USER_MODEL = "temp1app.AbstractUser1" # new
temp1/urls.py
from django.contrib import admin
from django.urls import path, include # new
from django.views.generic.base import TemplateView # new
from temp1app import URLs
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("temp1app.urls")), # new
path("accounts", include("django.contrib.auth.urls")), # new
path("", TemplateView.as_view(template_name="home.html"), name="home"),
# new
]
temp1app/admin.py
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR=os.path.join(BASE_DIR,'templates')
# 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-fzd#
(ie_srm3k^c+ggwzh5e$gu3j+dp#%!yg92r87r&61d16zr'
# 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',
'temp1app',
]
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 = 'temp1.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATES_DIR,],
'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 = 'temp1.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/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-
field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
#AUTH_USER_MODEL = "temp1app.AbstractUser1" # new
temp1app/forms.py
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = (
"username",
"email",
"age",
) # new
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = (
"username",
"email",
"age",
) # new
temp1app/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
age = models.PositiveIntegerField(null=True, blank=True)
temp1app/urls.py
from django.urls import path
from .views import SignUpView
urlpatterns = [
path("signup/", SignUpView.as_view(), name="signup"),
]
temp1app/views.py
from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import CustomUserCreationForm
class SignUpView(CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy("login")
template_name = "registration/signup.html"
templates/home.html
<!DOCTYPE HTML>
<HTML>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>Django</h1>
{% if user.is_authenticated %}
logout
{% else %}
login
signup
{% endif %}
{% block content %}
{% endblock}
</body>
</html>
templates/registration/signin.html
<!DOCTYPE HTML>
<HTML>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
{% extends 'home.html' %}
{% block content %}
<form method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="signin">
</form>
{% endblock %}
</body>
</html>
templates/registration/signup.html
<!DOCTYPE HTML>
<HTML>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
{% extends 'home.html' %}
{% block content %}
<form method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="signup">
</form>
{% endblock %}
</body>
</html>
You should add AUTH_USER_MODEL = "temp1app.CustomUser" to your settings.

After I submit form with uploading photos, there are nothing to save on Django database

I met a problem.
When I choose a photo as a profile_pic on the registration page,
it saves any information without a photo.
But I can't find out why it didn't work.
There is nothing in the Profile pic after submitting.
setting.py
"""
Django settings for learning_templates project.
Generated by 'django-admin startproject' using Django 3.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR=os.path.join(BASE_DIR,'templates')
STATIC_DIR=os.path.join(BASE_DIR,'static')
MEDIA_DIR=os.path.join(BASE_DIR,'media')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'pgmh_#pcqd(3sf(a3oj#^vyv4l-#p6g=n-=^!z)0d#!k)!_ear'
# 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',
'basic_app',
]
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 = 'learning_templates.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'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 = 'learning_templates.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
PASSWORD_HASHERS=[
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
'OPTIONS':{'min_length':9}
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS=[STATIC_DIR,]
#MEDIA
MEDIA_ROOT=MEDIA_DIR
MEDIA_URL='/media/'
LOGIN_URL='basic_app/user_login'
in views.py: register
def register(request):
registered= False
logging.error(request.method)
if request.method == 'POST':
user_form= UserForm(data=request.POST)
profile_form=UserProfileInfoForm(request.POST)
logging.error(user_form)
if user_form.is_valid() and profile_form.is_valid():
user=user_form.save()
user.set_password(user.password)
user.save()
profile=profile_form.save(commit=False)
profile.user=user
if 'profile_pics' in request.FILES:
profile.profile_pic=request.FILES['profile_pics']
profile.save()
registered=True
else:
print(user_form.errors,profile_form.errors)
else:
user_form=UserForm()
profile_form=UserProfileInfoForm()
return render(request,'basic_app/registeration.html',
{'user_form':user_form,
'profile_form':profile_form,
'registered':registered})
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfileInfo(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
# additional
portfolio_site=models.URLField(blank=True)
profile_pic = models.ImageField(upload_to = 'profile_pics', blank = True)
def __str__(self):
return self.user.username
forms.py
class UserProfileInfoForm(forms.ModelForm):
class Meta():
model=UserProfileInfo
fields=('portfolio_site','profile_pic')
registeration.html
<!DOCTYPE html>
{% extends "basic_app/base.html" %}
{% load static %}
{% block body_block %}
{{registered }}
<div class=jumbotron>
<h1>Test Register</h1>
{% if registered %}
<h1>Thank you for Register</h1>
{% else %}
<h1>Register Here</h1>
<h3>
<h1>Fill out the form</h1>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ user_form.as_p}}
{{ profile_form.as_p }}
<input type="submit" name="" value="Register">
</form>
</h3>
{% endif %}
</div>
{% endblock %}
And I have made sure that the profile_pics folder has nothing.
I don't know where I am wrong or what I miss but anything without a photo has saved.
If anything misses, please tell me.
Thank you for your time.
First check if the uploaded images is in your media/profile_pics folder.
Since you are viewing the data uploaded using the django admin panel ,it does not shows the actual image it will show the image name.
Try to display the image in a template by passing the user content in the context section while sending the rendering the template.

Static Files would not load in Django (Pycharm)

I am currently making a Web App using the Django framework and have just started recently. I looked through the Django Documentation and also looked through many tutorials and other answers on StackOverflow but none of them seem to work. When I first placed the link on the HTML page I included the {% static 'my_app/css/cssFile'%}and also included {% load staticfiles %}. I have also tried including this into my settings file: STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['static'])) but none of these work. Every time I try to run the server, the console keeps saying that the server could not find the resource and that it exited out as a 404.
This is my settings file:
"""
Django settings for WebApp project.
Generated by 'django-admin startproject' using Django 2.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
import posixpath
# 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 = '6-_^kvfdcg&#+_gdf1ub*ood*$fm4vs1m-aw_uw#(2tliu9(d0'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'WebApp',
'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 = 'WebApp.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 = 'WebApp.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/'
STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['static']))
My very simple HTML file that I am using for testing:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }} - My Django Application</title>
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'WebApp/css/layout.css' %}">
</head>
<body>
<div class="navbar clearfix">
<div class="container">
<div class="logo"></div>
<div class="menu-item">
<ul class="item-list">
Home
About
Question
</ul>
</div>
</div>
</div>
<div class="content">
<div class="container-content">
{% block content %}{% endblock %}
</div>
</div>
{% block scripts %}{% endblock %}
</body>
</html>
And the CSS file that I made:
div.navbar {
width: 100%;
color: #FFF;
height: 10px;
background-color: #000000;
}
.clearfix {
content: "";
clear: both;
display: table;
}
.container {
background-color: #000;
width: 100%;
height: 100%;
}
I have set up my directories as follows:
Any help would be greatly appreciated.
Check this im using this now and works.
Settings
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,"media")
and i call in this way
<link href="{% static 'app/vendor/bootstrap/css/bootstrap.min.css'%}" rel="stylesheet">
in urls
if settings.DEBUG:
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Change the next template tag:
{% load staticfiles %}
for:
{% load static %}

Send html input to views.py in Django

I'm trying to send input text from index.html to my view function that is "result".
When I click the 'Generate Summary' button its shows csrf verification failed.Csrf token missing.Urgent help required.
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from .models import Input
from django.views.decorators.csrf import csrf_protect
def home(request):
input=Input.objects.all()
template=loader.get_template('home/index.html')
context={
'input':input,
}
return HttpResponse(template.render(context,request))
def result(request,input_text):
Input.input_text = request.POST('input_text')
return HttpResponse("<h1> text is"+Input.input_text)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
{% load staticfiles %}
<link rel='stylesheet'href="{% static 'css/bootstrap.min.css' %}" type='text/css'/>
</head>
<body background="/static/home/img/bg.jpg">
<center><h1> <font color="white" >Summarizeit.com !</h1></center>
<form name="myform" action="." method="post">{% csrf_token %}
<div class="form-group">
<center><label for="abc">Input Text</label>
<input type="text" name="input_text"class="form-group" id="abc"placeholder="Text input">
</div>
<br><br>
<center><button type="submit" class="btn btn-default"> Generate Summary !</button>
</form>
</body>
</html>
home/urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
]
finalproject/urls.py(Root Project)
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', include('home.urls'))
]
models.py
from django.db import models
class Input(models.Model):
input_text = models.CharField(max_length=250)
def __str__(self):
return self.input_text
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/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y)m04wnmm%i_#uih%^j5&aqeozlp!gt#px&z!*uf=-%v98x#-i'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'home',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE_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 = 'finalproject.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 = 'finalproject.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/'
For some reason you're rendering your template the hard way, which bypasses all the automatic things that Django does for you: most importantly, running context processors that include the CSRF token.
Your view should be this:
def home(request):
input=Input.objects.all()
context={
'input':input,
}
return render(request, 'home/index.html', context)
Note also that your setting of Input.input_text in the result view makes no sense at all; you need to create an instance of Input, set its input_text, then save it.

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