I'm having trouble getting an image to display. This should be really easy to fix. I'm just a noob. :/
My models.py is the following:
import datetime
from django.db import models
from django.utils import timezone
class Coin(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
ticker = models.CharField(max_length=5)
logo = models.ImageField(upload_to='uploads/', verbose_name='image')
website = models.URLField(max_length=200, default="https://example.com/")
reddit = models.URLField(max_length=200, default="https://reddit.com/r/")
twitter = models.URLField(max_length=200, default="https://twitter.com/")
summary = models.CharField(max_length=500, blank=True)
description = models.TextField()
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.ticker
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class CoinImage(models.Model):
coin = models.ForeignKey(Coin, default=None, related_name='images',
on_delete=models.CASCADE)
image = models.ImageField(upload_to='static/uploads', verbose_name='image')
In my views.py I have:
from django.http import HttpResponse, Http404
from django.template import loader
from django.shortcuts import render
from .models import Coin
def index(request):
latest_coins_list = Coin.objects.order_by('-pub_date')[:5]
context = {'latest_coins_list': latest_coins_list}
return render(request, 'coins/index.html', context)
def detail(request, coin_id):
try:
coin = Coin.objects.get(pk=coin_id)
except Coin.DoesNotExist:
raise Http404("Coin does not exist")
return render(request, 'coins/detail.html', {'coin': coin})
My main urls.py is:
from django.contrib import admin
from django.urls import include, path
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('coins/', include('coins.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My app urls.py is:
from django.urls import path
from django.conf import settings
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<int:coin_id>/', views.detail, name='detail'),
]
Then finally in my template file details.html:
{% load static %}
<img src="{{ coin.logo.path }}" alt="La" />
<h1>{{ coin.name }} | {{ coin.ticker }}</h1>
<p>{{ coin.description }}</p>
<li><strong>Website:</strong> {{ coin.website }}</li>
<li><strong>Twitter:</strong> {{ coin.twitter }}</li>
<li><strong>Reddit:</strong> {{ coin.reddit }}</li>
When I view the template I get the alt text. Then when trying to access the image directly 127.0.0.1:8000/static/uploads/thumbs/me.jpg I get a template error saying:
Page not found (404) Request Method: GET Request URL:
http://127.0.0.1:8000/static/uploads/thumbs/me.jpg Raised by:
django.views.static.serve
'uploads/thumbs/me.jpg' could not be found
You're seeing this error because you have DEBUG = True in your Django
settings file. Change that to False, and Django will display a
standard 404 page.
This should be a really simple thing to do. If someone can point me in the right direction I would appreciate it so much. Sorry, am noob. :P
Added for someone:
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.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'i*a%3!kg*mj7j-=5b#_3cx(^%sqr*&sp$-fg*qv=qewm!a-_gt'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'coins',
'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 = 'blockintel.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 = 'blockintel.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static/')
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
During development, you can serve user-uploaded media files from MEDIA_ROOT. This is te absolute filesystem path to the directory that will hold user-uploaded files. in your settings, you should provide:
# MEDIA_ROOT = os.path.join(BASE_DIR,'your_directory')
MEDIA_ROOT = os.path.join(BASE_DIR,'media') # media most of the time
MEDIA_URL, URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slash if set to a non-empty value. You will need to configure these files to be served in both development and production environments. add this in your settings
# MEDIA_URL = '/your_url/'
MEIDA_URL = '/media/' # most of the time
You will need to do this as well by adding the following snippet to your root urls.py:
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
NOTE: This helper function works only in debug. Know more here
ISSUES / SUGGESTIONS
In this field, rather than uploading a file to static directory, just provide your media directory, in that case, it's media.
image = models.ImageField(upload_to='uploads/', verbose_name='image')
Django will automatically create a directory: 'uploads' inside the MEDIA_ROOT which is media,
So access all your the images that you have with
# file.url
{{ coin.logo.url }}
Related
I am trying to upload videos to my Django server directory. When I use the coded app in the admin panel, upload succeed at the correct location. However, when dealing with browser form, it will miss a level of the url as : 'media/title.mp4' instead of 'media/videos/title.mp4.
I'd like to save the files into 'media/videos/title.mp4'. Currently, front uploaded videos url is computed as 'media/title.mp4. It just fails, no resources created, even at the wrong location.
Here is my urls.py with the upload route :
from django.urls import path
from uploader.views import upload, download
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path('upload/', upload, name='upload'),
path('download/', download, name='download'),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Here is my upload view :
from django.shortcuts import render, redirect
from .models import VideoItem
def upload(request):
if request.method == 'POST':
title = request.POST['title']
video = request.POST['video']
content = VideoItem(title=title, video=video)
content.save()
return render(request, 'upload.html')
Here is my upload html template :
<form action="" method="POST">{% csrf_token %}
<input type="text" name="title" placeholder="Enter Video Title here"><br>
<input type="file" name="video" accept="video/mp4">
<button type="submit"> Upload New Video </button>
</form>
And here is my db model :
from django.db import models
# Create your models here.
class VideoItem(models.Model):
title = models.CharField(max_length=100)
video = models.FileField(upload_to='videos')
class Meta:
verbose_name = 'video'
verbose_name_plural = 'videos'
def __str__(self):
return self.title
My media root / directory config (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/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = someSecretKey
# 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',
'uploader.apps.UploaderConfig',
]
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 = 'pixblur_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 = 'pixblur_project.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 FILES (OPTIONAL)
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
# MEDIA FILES
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Any hints?
You should be using request.FILES not request.POST to access uploaded files. See more here.
def upload(request):
if request.method == 'POST':
title = request.POST['title']
video = request.FILES['video'] #<-- change it here
content = VideoItem(title=title, video=video)
content.save()
return render(request, 'upload.html')
As datosula mentioned, request.FILES fits here. However, to be able to get the ressource to write to the right directory with the right data (aka. request.FILES not being empty), i had to add the attribute enctype="multipart/form-data"> to my form.
I am new in Django Framework and currently working on first project. I made a simple contact form it takes data from users and save it into database. Everything is working right. But when I login into my admin panel and go into the Contacts and click on the data that I received. I am getting error "change_view() missing 1 required positional argument: 'object_id'".
my admin.py
from home.views import contact
from django.contrib import admin
from home.models import Contact
# Register your models here.
admin.site.register(Contact)
my models.py
from django.db import models
# Create your models here.
class Contact(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField()
phone = models.CharField(max_length=10)
desc = models.TextField()
my views.py
from home.models import Contact
from django.shortcuts import render, HttpResponse
from home.models import models
# Create your views here.
def home(request):
return render(request, 'home.html')
def about(request):
return render(request, 'about.html')
def projects(request):
return render(request, 'projects.html')
def contact(request):
if request.method=='POST':
print('This is POST')
name = request.POST['name']
email = request.POST['email']
phone = request.POST['phone']
desc = request.POST['desc']
# print(name, email, phone, desc)
contact = Contact(name=name, email=email, phone=phone, desc=desc)
contact.save()
print('DAta has been written into the Database')
# return HttpResponse("This is My Contact")
return render(request, 'contact.html')
my settings.py
"""
Django settings for pwhTutorials project.
Generated by 'django-admin startproject' using Django 3.1.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# 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/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '-snip-'
# 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 = [
'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 = 'pwhTutorials.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['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 = 'pwhTutorials.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
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.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
my urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name = 'home'),
path('about/', views.about, name = 'about'),
path('projects/', views.projects, name = 'projects'),
path('contact/', views.contact, name = 'contact'),
]
Project's urls.py
"""
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("home.urls"))
]
I am new in Django Framework and currently working on first project. I made a simple contact form it takes data from users and save it into database. Everything is working right. But when I login into my admin panel and go into the Contacts and click on the data that I received. I am getting error "change_view() missing 1 required positional argument: 'object_id'".
This is the image link https://ibb.co/LScd2Mb
You missed """ at the top of your projects urls.py. Please correct, hope this will solve your problem.
I am a beginner in Django. Right now, I am doing a simple app, called GameReview. It will allow the users to add the reviews of their favorite games. Right now, I am facing a 404 error.
It looks like this:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/gamereview/
Using the URLconf defined in gamerevs.urls, Django tried these URL patterns, in this order:
admin/
[name='hw']
gamereview [name='gamelist']
The current path, gamereview/, didn't match any of these.
Here are my codes of models.py inside gamereview folder:
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Tag(models.Model):
label = models.CharField(max_length=20)
def __str__(self):
return self.label
class Game(models.Model):
title = models.CharField(max_length=100)
developer = models.CharField(max_length=100)
platform = models.CharField(max_length=50, default='null')
label_tag = models.ManyToManyField(Tag)
slug = models.SlugField(max_length=150, default='null')
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)
class Review(models.Model):
game = models.ForeignKey(Game, on_delete=models.CASCADE)
review = models.CharField(max_length=1000)
date = models.DateField(auto_now=True)
slug = models.SlugField(max_length=150, default='null')
def __str__(self):
return self.review
def save(self):
super(Review, self).save()
self.slug = '%i-%s' % (
self.id, slugify(self.game.title)
)
super(Review, self).save()
Here are my codes of urls.py inside gamereview folder:
from . import views
from django.urls import path
urlpatterns = [
path('gamereview', views.gamelist, name='gamelist'),
]
Here are my codes of views.py inside gamereview folder:
from django.shortcuts import render
def gamelist(request):
context_dict = {'via': "Using template"}
return render(request, 'gamereview/gamelist.html', context_dict)
Here are the codes of settings.py in gamerevs folder:
"""
Django settings for gamerevs project.
Generated by 'django-admin startproject' using Django 2.2.7.
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 = 'su9+iji4y-5+ddebbavou+166_p2ph1n2cls3a^x_n9o6yl1nq'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'gamereview.apps.GamereviewConfig',
'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 = 'gamerevs.urls'
TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['/gamerevs/', TEMPLATE_PATH],
'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 = 'gamerevs.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_PATH = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = [
STATIC_PATH,
]
Here are my codes of urls.py under gamerevs folder:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('helloworld.urls')),
path('', include('gamereview.urls')),
]
Here are my codes of gamelist.html located inside gamereview folder of the templates folder.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Gamelist</title>
</head>
<body>
<h1>This is Game List Page</h1>
<strong>{{ via }}</strong><br />
<img src="{% static "images/Super_Mario_Odyssey.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
</body>
</html>
I thought that logging into Django admin and adding new games and reviews from there would fix the issue. However, after doing it, I am still getting the 404 error.
urlpatterns = [
path('gamereview', views.gamelist, name='gamelist'),
]
The URL path without trailing / (slash) will give 404 for URL ending with trailing slash.
gamereview will match only gamereview
gamereview/ will match gamereview/ and will redirect gamereview to gamereview/ matching both the types of URLs.
I recommend trailling slash in every URL path (in Django).
# You need to add your app name in your settings.py file 'INSTALLED_APPS'
INSTALLED_APPS = [
'gamereview.apps.GamereviewConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'gamereview',
]
Change urls.py file's (inside gamreview folder) content by;
urlpatterns = [
path('', views.gamelist, name='gamelist'),
]
and change urls.py file's (inside project directory) content to following;
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('helloworld.urls')),
path('gamereview/', include('gamereview.urls')),
]
I'm developing a simple form to upload files. I'm using Django 2.2.3.
I see that my form is valid because some print statments I've made, however I'm getting an error when saving the form.
ModuleNotFoundError at /admineditorial/predica/add/
No module named 'app'
And:
Exception Location: <frozen importlib._bootstrap> in _find_and_load_unlocked, line 965
I don't think it has to do something with Bootstrap. I don't know what could be happening.
Also, I'm uploading to /audio, but do I need to create this folder or is it generated automatically? if not, where should I create it?
Proyect structure:
-editorial
|_managment.py
|_migrations.py
|_templates
|_editorial
|_index.html
|_predicas
|_predicas.html
|_base.html
|_admin.py
|_forms.py
|_models.py
-el_comercio_app
|___init__.py
|_settings.py
|_storage_backends.py
|_urls.py
|_wsgi.py
models.py:
class Predica(models.Model):
audio_file = models.FileField(upload_to = u'audio/', max_length=200)
views.py:
# Create your views here.
def predica_upload(request):
predicas = Predica.objects.all()
if request.method == 'POST':
form = PredicaUpload(request.POST, request.FILES)
if form.is_valid():
print("### Form is valid ###")
form.save()
print("Despues del save")
print(form)
return redirect('today_editorial')
else:
print("### Form not valid ###")
print(form.errors)
else:
form = PredicaUpload()
return render(request, 'predicas/predicas.html', {'form': form, 'predicas': predicas})
urls.py:
from django.urls import path
from editorial import views
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin', admin.site.urls),
path("", views.today_editorial, name="today_editorial"),
path('predicas',views.predica_upload, name = 'predica_upload')
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
predicas.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<button type="submit">Subir</button>
</form>
{% for predica in predicas %}
<div>
<img src="{{predica.audio_file.url}}" alt="myvideo">
</div>
<p>No audios in my gallery yet :-(</p>
{% endfor %}
settings.py:
"""
Django settings for el_comercio_app project.
Generated by 'django-admin startproject' using Django 2.2.1.
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
from decouple import config
from dj_database_url import parse as dburl
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
ALLOWED_HOSTS = ['127.0.0.1', 'el-comercio-editoriales.herokuapp.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'editorial',
'storages'
]
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 = 'editorial.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'editorial', '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.media'
],
},
},
]
WSGI_APPLICATION = 'el_comercio_app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
# SECURITY WARNING: don't run with debug turned on in production!
default_dburl = 'sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3')
DATABASES = { 'default': config('DATABASE_URL', default=default_dburl, cast=dburl), }
####
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 = 'es-PE'
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/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATICFILES_LOCATION = 'static'
MEDIAFILES_LOCATION = 'media'
####
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media')
####
AWS_LOCATION = 'static'
AWS_ACCESS_KEY_ID ='XXXXXX'
AWS_SECRET_ACCESS_KEY = 'XXXXXXXXXXXXXXXXXXXX'
AWS_STORAGE_BUCKET_NAME ='universidad-elim-test-videos'
AWS_S3_CUSTOM_DOMAIN='%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
DEFAULT_FILE_STORAGE = 'app.storage_backends.MediaStorage'
STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATIC_URL='https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
AWS_DEFAULT_ACL = None
UPADTE 1
I had a file apps.py but deleted it bacuse maybe it was causing a conflict. However, it did not solve the problem.
apps.py:
from django.apps import AppConfig
class EditorialConfig(AppConfig):
name = 'editorial'
In your INSTALLED_APPS your app should be listed like this:
INSTALLED_APPS = [
...,
'editorial.apps.EditorialConfig'
]
You can read in the docs
First of all in your settings.py the ROOT_URLCONF is pointing to 'editorial.urls' but in your project structure I don't see the urls.py second in the error your are posting is talking about admineditorial/ directory and i don't see it in your project structure neither.
I am currently following the Django tutorial and when I get to the admin question area, there are no calendar button or today button shortcuts. I'm not sure where the problem is, so I'll list the files I've configured below
views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
admin.py
from django.contrib import admin
from .models import Question
admin.site.register(Question)
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__)))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '1*%8b#+%9&^5#5x7(yl)kxsa94qxz(tuz6hq%)x^kozg5q'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'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 = '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'
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 = 'America/New_York'
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/'
models.py
import datetime
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
# Create your models here.
#python_2_unicode_compatible
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
#python_2_unicode_compatible
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
mysite/urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
polls/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
In fact in order to display datetime picker and calender you need what is called in django widget. Django has support to built-in date widget but it's not so advanced.
So it's better to use third-party package with jQuery like django-datetime-widget.
install pip install django-datetime-widget
add datetimewidget to your INSTALLED_APPS in settings.py.
in forms.py:
from datetimewidget.widgets import DateTimeWidget
class QuestionForm(forms.ModelForm):
model = Question
class Meta:
model = yourModel
widgets = {
'datetime': DateTimeWidget(attrs={'id':"yourdatetimeid"}, usel10n = True, bootstrap_version=3)
}
in template file
<head>
....
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/js/bootstrap.min.js"></script>
....
</head>
In case you want to have the datetime widget in your admin interface so check here, it's a little bit hacky and require little bit more work.