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.
Related
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.
I know there are many posts about this, but I have been unable to resolve my problem (for example following this: Django static files (css) not working). I can't get my css static file to load on this practice page, css_practice.html.
I have the following structure
djangoAjax
settings.py
...
djangoAjaxApp
static
ok.css
templates
css_practice.html
My settings.py:
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = '############################################'
# 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',
"crispy_forms",
'djangoAjaxApp',
]
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 = 'djangoAjax.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 = 'djangoAjax.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'), BASE_DIR / "static",
]
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
)
my html page:
<!DOCTYPE html>
{% load static %}
<html>
<head>
{% comment %} https://www.bing.com/videos/search?q=django+static+css&docid=608004894969656896&mid=E118E7C4ADFE161B3B12E118E7C4ADFE161B3B12&view=detail&FORM=VIRE {% endcomment %}
{% load static %}
<link type="text/css" rel="stylesheet" href"{% static 'djangoAjaxApp\static\ok.css' %}">
<title>Page Title</title>
</head>
<body>
<h1 class="ok">My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
views.py:
# css practice
def cssRender(request):
return render(request, "css_practice.html")
urls.py:
from django.urls import path
from .views import cssRender
urlpatterns = [
path('css/', cssRender, name='cssRender'),
]
I imagine I might be messing up the folder structure somehow... there is also a reference in the django docs: https://docs.djangoproject.com/en/3.2/howto/static-files/
about adding
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
But since I am using, django.contrib.staticfiles in settings, I'm assuming this is done automatically.
Currently the page loads, but css is not applied.
Thanks for your help
settting.py:
STATIC_URL = '/static/'
Only one {% load static %} is enough in your html code:
<!DOCTYPE html>
{% load static %}
You have to Copy and Plast your STATIC files (Js, CSS, ...) in your templates.
It will look like that :
djangoAjaxApp
|_migrations
|_templates
| |_djangoAjaxApp
| |_css_practice.html
|_static
|___djangoAjaxApp (directory with the same App name)
|_(here all your static file)
Your HTML will look like this:
<link type="text/css" rel="stylesheet" href"{% static 'djangoAjaxApp\ok.css' %}">
views.py:
# css practice
def cssRender(request):
return render(request, "djangoAjaxApp/css_practice.html")
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.cssRender, name='cssRender'),
]
djangoAjax urls.py:
from django.conf import settings
from django.contrib import admin
from django.urls import path
urlpatterns = [
# ... the rest of your URLconf goes here ...
]
Could you please try it.
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
Just to remind you of it, have you tried hard refresh on your browser? I used to miss this when I was a beginner. (You can do it in chrome with ctrl+shift+r).
I am struggling for 5 days, cant make it work. My code works perfectly fine on local server, but wont work when i upload application. It just won't accept any new data i just face some weird redirections to homepaage with the url of the page i made submit. The existing(imported) data can be manipulated and changed, just no way to submit new data.
{% extends "baza.html" %}
{% block content %}
{% load static %}
{% load crispy_forms_tags %}
<div class="container-login100" style="background-image: url('/static/images/pticica.jpg');">
<div class="wrap-login100">
<form method="POST" action="{% url 'Registracija' %}" enctype="multipart/form-data" class="login100-form">
{% csrf_token %}
<span class="login100-form-logo">
<i class="zmdi zmdi-landscape">
<img style="border-radius:100%;padding:5px;" src="/static/images/login.png">
</i>
</span>
<span class="login100-form-title p-b-34 p-t-27">Registruj se</span>
{{form|crispy}}
<button type="submit" class="btn btn-success">Registruj se</button>
</form>
</div>
</div>
{% endblock %}
my views
from django.shortcuts import render, redirect
from .forme import RegisterForm
def register(request):
if request.method == "POST":
form = RegisterForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect("login")
else:
form=RegisterForm()
return render(request,"register/register.html", {'form':form})
and global settings
from django.utils.translation import ugettext_lazy as _
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/{{ docs_version }}/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '{{ secret_key }}'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['ljubimac.me','www.ljubimac.me']
# Application definition
INSTALLED_APPS = ['Websajt',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'register',
'crispy_forms',
'allauth',
'allauth.account' ,
'allauth.socialaccount' ,
'allauth.socialaccount.providers.github',
'Users',
]
SITE_ID = 1
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Sajt.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 = 'Sajt.wsgi.application'
# Database
# https://docs.djangoproject.com/en/{{ docs_version }}/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'deniggsm_ljubimac',
'HOST': 'localhost',
'USER': 'deniggsm_Andrija_Culafic',
'PASSWORD':'protokol123',
'PORT': '3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/{{ docs_version }}/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/{{ docs_version }}/topics/i18n/
LANGUAGE_CODE = 'sr'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LOCALE_PATHS=[
os.path.join(BASE_DIR,'locale')
]
STATIC_URL=('/static/')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
#email
EMAIL_HOST='smtp.gmail.com'
EMAIL_PORT='465'
EMAIL_HOST_USER="selastan#gmail.com"
EMAIL_HOST_PASSWORD="extractor361"
EMAIL_USE_SSL="True"
DEFAULT_FROM_EMAIL = 'noreply<no_reply#domain.com>'
SITE_ID = 1
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
LOGIN_REDIRECT_URL='/'
LOGOUT_REDIRECT_URL='/login'
ADMIN_MEDIA_PREFIX = '/media/'
AUTH_USER_MODEL = 'Users.NewUser'
url patterns
from django.urls import include,path
from . import views
from django.contrib import admin
from django.conf.urls.static import static
from register.views import register
from django.conf import settings
urlpatterns = [
path('',views.Naslovna,name='Naslovna'),
path('postavi-oglas/',views.Oglasss,name='Oglasss'),
path('svi-oglasi/<slug:slug>/',views.Pojedinacni_Oglas,name='Pojedinacni'),
path('svi-oglasi',views.Sviii,name='Svi_Oglasi'),
path('svi-oglasi/sortiranje',views.Sortiranje,name='Sortiranje'),
path('registracija/',register,name="Registracija"),
path('admin/',admin.site.urls),
path('moj-profil',views.MojProfil,name='Profil'),
path('promijeni-lozinku/',views.PromijeniSifru,name="Lozinka"),
path('kategorije/',views.Kategorije,name="Kategorijaaa"),
path('Psi/',views.Psi,name="Psiii"),
path('Mačke/',views.Mačke,name="Mačkeee"),
path('Ptice/',views.Ptice,name="Pticeee"),
path('Reptili/',views.Reptili,name="Reptiliii"),
path('Ribice/',views.Ribice,name="Ribiceee"),
path('Glodari/',views.Glodari,name="Glodariii"),
]
url.py in root
from django.urls import include,path
from django.contrib import admin
from django.conf.urls import include
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls.static import static
urlpatterns = [
path('',include('Websajt.urls')),
path('',include('django.contrib.auth.urls')),]
urlpatterns+=static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
edited register view
from django.shortcuts import render, redirect
from .forme import RegisterForm
def register(request):
if request.method == "POST":
form = RegisterForm(request.POST, request.FILES)
if form.is_valid():
form.save()
print(form.errors)
return redirect("login")
else:
form=RegisterForm()
return render(request,"register/register.html", {'form':form})
Even though I am providing correct path it still giving me an error. in this project have made custom user model so I am not able to understand where i am going wrong.
And also added the required paths in settings. I tried the same code even by using include method in urls,py but still failed. where exactly i am making mistake?
setting.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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'fw4g6x*9vn6sz)&v*$q-gppcwgd-%0&oo6_ydt(3t!#&uyz=xt'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
AUTH_USER_MODEL = 'account.Account'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'account',
]
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 = 'project.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 = 'project.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')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
register.html:
{% block content %}
<h1>Register</h1>
<form action="register1" method="post">
{% csrf_token %}
{% for field in registeration_form %}
<p>
{{field.label_tag}}
{{field}}
{if field.help_text %}
<small style="color:grey;">{{field.help_text}}</small>
{% endif %}
{% fr error in field.errors %}
<p style="color:red;">{{error}}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit">Register</button>
</form>
{% endblock %}
urls.py
from django.contrib import admin
from django.urls import path
from account.views import (
register,
)
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', register, name='register'),
]
views.py
from django.shortcuts import render, redirect
#from django.contrib.auth.models import User, auth
from django.contrib.auth import login, authenticate
from account.forms import RegistrationForm
def register(request):
context ={}
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
aadhar = form.cleaned_data('aadhar')
raw_password = form.cleaned_data('password1')
account = authenticate(aadhar=aadhar,password=raw_password)
login(request, account)
return redirect('/')
else:
context['registration_form'] = form
else:
form = RegistrationForm()
context['registration_form'] = form
return render(request, 'account/register.html', context)
Error:
TemplateDoesNotExist at /register/
account/register.html
Request Method: GET
Request URL: http://127.0.0.1:8000/register/
Django Version: 3.0.4
Exception Type: TemplateDoesNotExist
Exception Value:
account/register.html
Exception Location: E:\phptodj\test1\venv\lib\site-packages\django\template\loader.py in get_template, line 19
Python Executable: E:\phptodj\test1\venv\Scripts\python.exe
Python Version: 3.7.4
Python Path:
['E:\\phptodj\\test1',
'E:\\phptodj\\test1',
'C:\\ProgramData\\Anaconda3\\python37.zip',
'C:\\ProgramData\\Anaconda3\\DLLs',
'C:\\ProgramData\\Anaconda3\\lib',
'C:\\ProgramData\\Anaconda3',
'E:\\phptodj\\test1\\venv',
'E:\\phptodj\\test1\\venv\\lib\\site-packages']
Server time: Tue, 17 Mar 2020 12:32:53 +0000
Your settings of the template in settings.py should be...
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
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',
],
},
},
]
And your folder structure should be...
project_name
|
app_1
|
app_2
|
account
|
templates
|
|__account
|
|__register.html
I am getting the following error after I added href="{% url 'cart-add' product.id %}" to the add to cart button on my product.html file:
NoReverseMatch at /3/
Reverse for 'cart-add' with arguments '('',)' not found. 1 pattern(s) tried: ['cart\\/add\\/(?P<product_id>[0-9]+)\\/$']
I believe that it's a urls pathing problem or settings, but I'm not sure how to resolve it. In case there are relevant files I missed displaying here, here is my github: https://github.com/sebapaik/django-shop
My product.html file looks like this:
{% extends "shop/base.html" %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-lg-4">
<img class="img-thumbnail" src="{{ object.imageurl }}" alt="">
</div>
<div class="col-lg-8">
<h2>{{ object.brand }} {{ object.pname }}</h2>
<p>${{ object.price }}</p>
<p>{{ object.description }}</p>
**likely the problem below**
<button class="btn" style="background:#f0c14b; border-color:#a88734;" href="{% url 'cart:cart-add' product.id %}">Add to cart</button>
</div>
</div>
{% endblock content %}
My Project/urls.py (main) looks like this:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('shop.urls')),
path('cart/', include('cart.urls')),
]
My shop/urls.py looks like this:
from django.urls import path
from .views import ProductListView, ProductDetailView
from . import views
urlpatterns = [
path('', ProductListView.as_view(), name = 'shop-index'),
path('<int:pk>/', ProductDetailView.as_view(), name = 'shop-product'),
]
My cart/urls.py looks like this:
from django.urls import path
from . import views
urlpatterns = [
path('add/<int:product_id>/', views.add_cart, name='cart-add'),
path('', views.cart_detail, name='cart-detail'),
]
My settings.py looks like this:
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#9k!nb!1wi5*d=+*#3j+$gl%(#$z(c1aqsyh1p+qqs#)yeuh*_'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'shop.apps.ShopConfig',
'cart.apps.CartConfig',
'crispy_forms',
'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 = 'Project.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 = 'Project.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/'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
I am using Django 2.1.1, Python 3.6, and Windows 10
Your product.id is empty according to the error message. You should use object.id instead in your template:
<button class="btn" style="background:#f0c14b; border-color:#a88734;" href="{% url 'cart:cart-add' object.id %}">Add to cart</button>
It seems that Django recognise your request url is '/3/', what you want to reverse is 'car/add/3/', you could try simply use [href="/cart-add/{{product.id}}'"] to replace [href="{% url 'cart-add' product.id %}"].By the way, while your 'shop/urls.py' and 'cart/urls.py' has the same line "path('add//', views.add_cart, name='cart-add'),"? It may lead to some other problems.