Django Static file not loading ImageField URL - python

This is for an assignment, we need to store the images in the static directory and display them on a template. The images are stored through the item model ImageField and uploaded to the static/images directory.
Here is the template code:
{% load static %}
<p><a href='..'>Home</a></p>
{% block content %}
<table>
<tr>
<th>Item Name</th>
<th>Manufacturer</th>
<th>Cost</th>
<th>Weight</th>
<th>Image</th>
</tr>
{% for i in name %}
{% if i.name == params %}
<tr>
<td>{{i.name}}</td>
<td>{{i.manufacturer}}</td>
<td>{{i.cost}}</td>
<td>{{i.weight}}</td>
<td><img src="{% static i.image.url %}" alt="{{i.image.url}}"></img></td>
</tr>
{% endif %}
{% endfor %}
</table>
{% endblock %}
I have the following model code:
from django.db import models
class item(models.Model):
name = models.CharField(max_length=40)
manufacturer = models.CharField(max_length=255)
cost = models.DecimalField(max_digits=10, decimal_places=2)
weight = models.DecimalField(max_digits=10, decimal_places=2)
image = models.ImageField(upload_to='static/images/')
Here are the current 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 = 'Nice try'
# 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',
'mysite',
]
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': [],
'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_HOSTS = ['*']
X_FRAME_OPTIONS = '*'
Currently, everything is displaying properly from the model class, however the images will not load after trying a million different tags for the img src. We are supposed to use static so please do not suggest using media directory for the images.
Thank you for the help.

Assuming in your views.py you have:
name = item.objects.all()
and then that the variable name is passed to your template,
try to substitute this
<td><img src="{% static i.image.url %}" alt="{{i.image.url}}"></img></td>
With this
<td><img src="{{ i.image.url }}" alt="{{i.image.url}}"></img></td>
However, I would suggest you to call the name variable by something more representative, like objects_list, then you will have
{% for i in objects_list %}
{% if i.name == params %}
<tr>
<td>{{i.name}}</td>
<td>{{i.manufacturer}}</td>
<td>{{i.cost}}</td>
<td>{{i.weight}}</td>
<td><img src="{% static i.image.url %}" alt="{{i.image.url}}"></img></td>
</tr>
{% endif %}
{% endfor %}
this is way more clear.

Related

How to display images uploaded from django admin to heroku?

I deployed my django project on heroku. The site is all working well except for the fact that some images are broken. These images are all images which I uploaded to my site in local server via the django admin. These images were uploaded to my site on local server by providing the url in image field in django admin page. All the images which are hard coded in the html code and are static/images folder in my project are displayed. Any changes I should make to my settings.py file to dipslay these pictures? How to resolve this?
My settings.py file
"""
Django settings for ecommerce project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/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/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'gm1zyhprh9=9+4#vu*^8g30(pg*xq6e#0z1)h81hc2evd7n*^v'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['market-shaurya.herokuapp.com', '127.0.0.1']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_filters',
'store.apps.StoreConfig',
]
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 = 'ecommerce.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 = 'ecommerce.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/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.2/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.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/2.2/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
MEDIA_URL='/images/'
MEDIA_ROOT=os.path.join(BASE_DIR, 'static/images')
my store.html templates file
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<div class="row">
{% for product in products %}
<div class="col-lg-4">
<img class="thumbnail" src="{{product.imageURL}}">
<div class="middle">
<div class="text"><strong><strong>{{product.description}}</strong></strong></div>
</div>
<div class="box-element product">
<h6><strong>{{product.name}}</strong></h6>
<hr>
<button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button>
<a class="btn btn-outline-success" href="#">View</a>
<h4 style="display: inline-block; float: right"><strong>₹{{product.price|floatformat:2}}</strong></h4>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
notice this src="{{product.imageURL}}. This is how I uploaded pictures to this cart.
DEBUG = True
This solves the problem.

After logging in (in my Django app) I get the 403 error

When I run my Django application (via python manage.py runserver) I get the login screen, however when I try to login it redirect me to the page that says:
Forbidden (403)
CSRF verification failed. Request aborted.
Here is my settings.py
"""
Django settings for my_app project.
Generated by 'django-admin startproject' using Django 2.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# 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 = '...'
# 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',
'cooking_book'
]
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 = 'my_app.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',
'django.template.context_processors.static',
'django.template.context_processors.media',
],
},
},
]
WSGI_APPLICATION = 'my_app.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/
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
STATIC_URL = '/static/'
There are questions similar to mine here on stackoverflow but unfortunately the answers are not helpful to me...
Additional notes on what I tried:
I am allowing cookies in my browser.
My view functions pass a request to the template's render method.
In the template I am adding {% csrf_token %} inside each POST form.
I also tried setting the CSRF_COOKIE_DOMAIN = None and CSRF_COOKIE_SECURE = False but it made no difference.
It would be great if anyone could help me with this, I am really stuck...
EDIT:
If you give me thumbs down, can you please just let me know what I did wrong? I am new here, still adapting... and if this is too easy for you and that is the reason for the thumbs down, please leave an answer I will appreciate it. Thank you!
2nd EDIT: Adding the relevant parts of the template and views.py file, where the csrf token is used. It is also worth mentioning that when the user logs in he/she is supposed to go to the homepage (that contains no POST forms and consequently no csrf tokens), and chose where to go next.
views.py (relevant part)
#login_required(login_url='/login/')
def dining(request):
#request is POST when user filters the city
if request.method == 'POST':
filter_city = FilterCityForm(request.POST)
if filter_city.is_valid():
filter_city = filter_city.save(commit=False)
city = str(filter_city.name)
#...
# here I'm doing some calculations and querying depending on the chosen city
#...
filter_city = FilterCityForm(initial={'name':city})
else:
filter_city = FilterCityForm(initial={'name':'Toronto'})
return render(request, 'dining.html', {'filter_city':filter_city})
dining.html (relevant part):
<div name='dropdown'>
<form action="" method="POST">
{% csrf_token %}
City: {% for widget in filter_city %}
{% if widget.errors %}
{% for error in widget.errors %}
<span style="color: red">{{ error }}</span><br>
{% endfor %}
{% endif %}
{{ widget }}
{% endfor %}
<input type="submit" value="OK">
</form>
<br>
</div>

Not properly render image from Django model

I am making a simple app(Django version 1.11+python3.5+). I want to show images on my homepage(web app) from Django models. I can upload successfully from Django admin panel. But image cant renders properly. The image does not show in the homepage. This is my HTML file.
{% extends "shop/base.html" %}
{% block content_area %}
{% for name in products %}
<div class="col-lg-3 col-md-3">
<div class="main_content_sidebar">
<div class="content_title">
<h2>{{name.product_name}}</h2>
</div>
<div class="image_space">
<img src="{{name.product_image.url}}" class="img-thumbnail" alt="">
</div>
<div class="content_p">
<p>Retail Price:{{name.product_retail_price}}</p>
<p>Quantity: {{name.product_quantity}}</p>
<p>Date: {{name.product_sell_date}}</p>
</div>
</div>
</div>
{% endfor %}
{% endblock %}
this is mysite(project)>>urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^shop/',include('shop.urls')),
url(r'^admin/', admin.site.urls),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
This is my models.py file.
class ProductsName(models.Model):
product_name=models.CharField('name', max_length=50)
product_retail_price=models.IntegerField('retail price TAKA')
product_quantity = models.IntegerField('quantity')
product_sell_date=models.DateTimeField('buy date', auto_now_add=True)
product_image = models.ImageField(upload_to='upload/', blank=True, null=True)
def __str__(self):
return self.product_name
setting.py file
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.11.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/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/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'shop.apps.ShopConfig',
'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 = '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.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Dhaka'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'shop/images/')
MEDIA_URL = '/media/'
When I visit my homepage, I can't see any image. But I see image link If I open my browser dev tools.
chrome dev tool
if I click that image link from chrome dev tool. I got andjango doesn/t found that image url error.
Also my folder structure is:
mysite
shop
manage.py
path_to
db.sqlite3
The issue is that the your MEDIA_ROOT is not being served and Django cannot append the correct url. In your project urls.py add the following at the end:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And in the setttings.py add the correct paths for:
MEDIA_ROOT = os.path.join(BASE_DIR,'path_to_/media_folder')
MEDIA_URL = '/media/'

Django Session variables not updating properly

I am trying to figure out how sessions work. Basically I am trying to make a restaurant menu and store ordered food into session for further use. However, I ran into a problem and I cant figure out what might be the problem.
The problem is that if I submit the form 1st time. The success view shows the correct data.
I click Submit (pridat) and it works correctly
The output is:
('2', 1)
Where number 2 is food ID and 1 is the quantity.
Then I go back to the menu and I want to update the quantity to lets say 3
I change quantity (mnozstvo) to 3 and submit
But the output is still:
('2', 1)
The weirdest thing that has me confused is the fact that for example different food, even though it should be generated the same way works and updates just fine.
If I want to "order" multiple things it works fine with some and sometime one or multiple just refuse to update properly. As I am writing this 3 out of 4 works just fine.
('3', 5)('4', 8)('1', 15)('2', 1)
I can change 3-5, 4-8 and 1-15 but the 2-1 just never ever changes.
If I restart the built in django server sometimes different pair does not update properly. This time it is 2-1 but I also had an issue that 3-5 would not update.
So I would be really happy if someone could tell me what am I doing wrong? I know I am not letting django generate form but I rather do it manually in html, but that should not be the problem, should it?
menu.html with form separated for better visibility
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'restaurant/style.css' %}" />
{% if all_food_list %}
<center>
<ul>
<li>Home</li>
<li>Menu</li>
<li style="float:right"><a class="active" href="#about">Objednavka</a></li>
</ul>
<div class="clearfix">
{% for food in all_food_list %}
<div class="div1">
<center>
<img src="{{ MEDIA_URL }}{{ food.picture.url }}" alt="{{ food.name }}">
<h2> {{ food.name}} </h2>
<p>Cena: {{ food.price }}czk</p>
<p>Hmotnost: {{ food.weight}}g</p>
<p>Zlozenie: {{ food.ingredients}}</p>
<form action="/get_food/" method="post">
{% csrf_token %}
Mnozstvo: <input id="test" type="number" name="quantity" min="0" max="30" step="1" value="1">
<input type="hidden" name="food_type" value="{{ food.id }}">
<input type="submit" value="Pridat">
</form>
</center>
</div>
{% endfor %}
TODO: Funkcny formular, view pre objednavku, nastavit limity div-ov.
</div>
</center>
{% else %}
<p>No food available.</p>
{% endif %}
My views.py
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from .models import Food
from .forms import FoodOrder
def index(request):
template = loader.get_template('restaurant/index.html')
request.session.flush()
return HttpResponse(template.render(request))
def menu (request):
all_food_list = Food.objects.order_by('name')
template = loader.get_template('restaurant/menu.html')
context = {
'all_food_list': all_food_list,
}
return HttpResponse(template.render(context, request))
def get_food(request):
if request.method == 'POST':
form = FoodOrder(request.POST)
if form.is_valid():
quantity = form.cleaned_data['quantity']
#Food_type is db food id
food_type = form.cleaned_data['food_type']
#add to the session
request.session[food_type] = quantity
return HttpResponseRedirect('/success/')
else:
return HttpResponseRedirect('/index/')
def success(request):
#just writes the content of session
obsah = request.session.items()
return HttpResponse(obsah)
# Create your views here.
forms.py
from django import forms
class FoodOrder(forms.Form):
quantity = forms.IntegerField()
food_type = forms.IntegerField()
settings.py
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'restaurant.apps.RestaurantConfig',
'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 = 'iis_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 = 'iis_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/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.10/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = 'D:\Škola\IIS\Projekt - Restaurace\media'
MEDIA_URL = '/media/'

Installed Django AllAuth, can't find login or signup

I just installed Django AllAuth to my project, but cant find default login or signup page.
1) I logged out from admin panel, but still didn't find it.
2) Added signup.html template, but nothing
Picture of error in localhost/accounts http://prntscr.com/9oyu00
Here's my code:
settings.py
# 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',
'profiles',
'contact',
'crispy_forms',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
]
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 = 'src.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 = 'src.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.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',
},
]
# 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/
STATIC_URL = '/static/'
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static-only")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media")
STATICFILES_DIRS = (os.path.join(os.path.dirname(BASE_DIR), "static", "static"),
)
# Location of templates
CRISPY_TEMPLATE_PACK = 'bootstrap3'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
)
SITE_ID = 1
LOGIN_URL = '/accounts/login'
LOGIN_REDIRECT = '/'
ACCOUNT_AUTHENTICATION_METHOD = "username_email"
ACCOUNT_CONFIRM_EMAIL_ON_GET = False
ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = LOGIN_URL
ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = None
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 3
ACCOUNT_EMAIL_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = None
ACCOUNT_EMAIL_SUBJECT_PREFIX = "My subject: "
ACCOUNT_DEFAULT_HTTP_PROTOCOL = "http"
ACCOUNT_LOGOUT_ON_GET = False
ACCOUNT_LOGOUT_REDIRECT_URL = "/"
ACCOUNT_SIGNUP_FORM_CLASS = None
ACCOUNT_SIGNUP_PASSWORD_VERIFICATION = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USER_MODEL_USERNAME_FIELD = "username"
ACCOUNT_USER_MODEL_EMAIL_FIELD = "email"
ACCOUNT_USERNAME_MIN_LENGTH = 5
ACCOUNT_USERNAME_BLACKLIST = []
ACCOUNT_USERNAME_REQUIRED = True
ACCOUNT_PASSWORD_INPUT_RENDER_VALUE = False
ACCOUNT_PASSWORD_MIN_LENGTH = 6
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from contact import views
urlpatterns = [
url(r'^$', 'profiles.views.home', name='home'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^accounts/', include('allauth.urls')),
url(r'^admin/', admin.site.urls),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
signup.html
{% extends "account/base.html" %}
{% load crispy_forms_tags %}
{% load i18n %}
{% block head_title %}{% trans "Signup" %}{% endblock %}
{% block content %}
<h1>{% trans "Sign Up" %}</h1>
<p>{% blocktrans %}Already have an account? Then please sign in.{% endblocktrans %}</p>
<form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}">
{% csrf_token %}
{{ form|crispy }}
{% if redirect_field_value %}
<input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
{% endif %}
<button class='btn btn-default' type="submit">{% trans "Sign Up" %} »</button>
</form>
{% endblock %}
I had the same problem. The source of it all was that I had already defined a base.html file without a 'block content' block. You need the following structure inside the body of your base.html file:
<body>
{% block body %}
{% block content %}
{% endblock content %}
{% endblock body %}
</body>
I used this source to find a suitable example, but it's not very helpful other than that. This other page was a bit better though.
Because you are requesting only the /accounts/ and if you see closely to your debugger (the screen) there is no URL for this (pattern ^accounts/ ^ ^$).
Your login & sing up page is located on /accounts/login/ and /accounts/singup/.
About editing default templates I am not able to help you with it (never used the AllAuth package) so hope someone skilled will help you.

Categories

Resources