Django NoReverseMatch Reverse for 'cart-add' with arguments '('',)' not found - python

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.

Related

NoReverseMatch at /login/ Reverse for '' not found. '' is not a valid view function or pattern nam

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 can't add new data to mysql, though I can manipulate existing (imported) data

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})

static files in the media folder not showing when i upload on live server

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/

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