I have been using this code to produce a file uploader and I can only get as far as getting the template to attempt an upload. I am wondering if I need to either configure Apache, add something to Django settings or install some more libraries maybe?
I have followed all the steps mentioned on that page, but please ask if you suspect I may have carried one or two of them out incorrectly.
Error
jssor.slider.js
Error INTERNAL SERVER ERROR
Settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_file_form',
'django_file_form.ajaxuploader',
'jfu',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.core.context_processors.static',
'django.contrib.auth.context_processors.auth',
)
MIDDLEWARE_CLASSES = (
'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',
)
STATIC_ROOT = '/Users/Jonathan/Documents/django/bible/bible/static/jfu'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(os.path.dirname(__file__), 'static').replace('\\','/'),
)
views.py
from django.conf import settings
from django.core.urlresolvers import reverse
from django.views import generic
from django.views.decorators.http import require_POST
from jfu.http import upload_receive, UploadResponse, JFUResponse
#require_POST
def upload( request ):
# The assumption here is that jQuery File Upload
# has been configured to send files one at a time.
# If multiple files can be uploaded simulatenously,
# 'file' may be a list of files.
file = upload_receive( request )
instance = YOURMODEL( file = file )
instance.save()
basename = os.path.basename( instance.file.path )
file_dict = {
'name' : basename,
'size' : file.size,
'url': settings.MEDIA_URL + basename,
'thumbnailUrl': settings.MEDIA_URL + basename,
'deleteUrl': reverse('jfu_delete', kwargs = { 'pk': instance.pk }),
'deleteType': 'POST',
}
return UploadResponse( request, file_dict )
#require_POST
def upload_delete( request, pk ):
success = True
try:
instance = YOURMODEL.objects.get( pk = pk )
os.unlink( instance.file.path )
instance.delete()
except YOURMODEL.DoesNotExist:
success = False
return JFUResponse( request, success )
urls.py
from django.conf.urls import patterns, include, url
from bible import views
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'bible.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^verses/', views.index),
url(r'^search/', views.search),
url(r'^contact/', views.contact),
url(r'^profile/', views.profile),
url(r'^register', views.register),
url( r'upload/', views.upload, name = 'jfu_upload' ),
# You may optionally define a delete url as well
url( r'^delete/(?P<pk>\d+)$', views.upload_delete, name = 'jfu_delete' ),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
models.py
from django.db import models
from django.forms import ModelForm
from django.conf import settings
# Create your models here.
class Photo( models.Model ):
file = models.FileField( upload_to = settings.MEDIA_ROOT )
The issue was with the database. I think it was corrupted somehow and wouldn't talk with the application properly. Rebuilding it and running python manage.py migrate seemed to do the trick.
Related
I'm trying a build a login/logout application in django.
This is my view.py file code:
from django.core.contex_processors import csrf
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.contrib import auth
def login(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def auth_view():
username = request.POST.get('username','')
password = request.POST.get('password','')
user = auth.authenticate(username = username, password=password)
if user is not None:
auth.login(request, user)
return HttpResponseRedirect('/accounts/loggedin','')
else:
return HttpResponseRedirect('/accounts/invalid')
def loggedin(request):
return render_to_response('loggedin.html', {'full_name': request.user.username})
def invalid_login(request):
return render_to_response('invalid_login.html')
def logout(request):
auth.logout(request)
return render_to_response('logout.html')
and this is the error that throws when i run any url as below:
Request URL: http://127.0.0.1:8000/accounts/login/
Django Version: 1.6.6
Exception Type: ImportError
Exception Value: No module named contex_processors
Exception Location: /home/mjrulesamrat/django_mj/django_test/django_test/views.py in <module>, line 1
And here is my settings.py file where i have added middleware related to csrf and authentication as well as in Installed_app.
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'article',
)
MIDDLEWARE_CLASSES = (
'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',
)
so i shown settings.py, views.py and error on my browser. Please help.
oh yes and i foeget to mention url.py file..
Here it is.
from django.conf.urls import patterns, include, url
from article.views import HelloTemplate
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^articles/', include('article.urls')),
# Examples:
# url(r'^$', 'django_test.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^hello/$', 'article.views.hello'),
url(r'^hello_template/$', 'article.views.hello_template'),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/login', 'django_test.views.login'),
url(r'^accounts/logout', 'django_test.views.logout'),
url(r'^accounts/auth', 'django_test.views.auth_view'),
url(r'^accounts/loggedin', 'django_test.views.loggedin'),
url(r'^accounts/invalid', 'django_test.views.invalid_login'),
)
This looks fine..only error is in views.py file's line 1.
You have a typo, it should be: from django.core.context_processors import csrf.
Im getting a
templatedoesnotexistat / login.html
I copied and paste the settings from another project that worked and can not figure out why it can not find the template files. I have gone over it many times and copied the paths so they should defiantly be right. Its driving me mad
My file structure is
-virtual
-src
-logins
-dashboards
-static
-templates
-login.html
-static
-static-only
-media
settings.py
import os
BASE_DIR = '/Users/user/Documents/Python/virtual/'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'logins',
'dashboards',
)
ROOT_URLCONF = 'src.urls'
STATIC_URL = '/static/'
TEMPLATE_DIR = (
'/Users/user/Documents/Python/virtual/src/static/templates',
)
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = '/Users/user/Documents/Python/virtual/src/static/static-only/'
MEDIA_ROOT = '/Users/user/Documents/Python/virtual/src/static/media/'
STATICFILES_DIRS = (
'/Users/user/Documents/Python/virtual/src/static/static/',
)
urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'logins.views.login', name='login'),
url(r'^/accounts/auth/$', 'logins.views.auth_view', name='auth_view'),
url(r'^/accounts/dashboard/$', 'dashboards.views.dashboard', name='dashboard'),
url(r'^/accounts/logout/$', 'logins.views.logout', name='logout'),
url(r'^/accounts/invalid/$', 'logins.views.invalid', name='invalid'),
url(r'^admin/', include(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)
views.py
from django.shortcuts import render, render_to_response, RequestContext
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
def login(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return HttpResponseRedirect('/accounts/dashboard')
else:
return HttpResponseRedirect('/accounts/invalid')
def logout(request):
return render_to_response('logout.html')
def invalid(request):
return render_to_response('invalid.html')
You have TEMPLATE_DIR in your settings. It should be TEMPLATE_DIRS.
I doubt your template directory is inside the static directory: remove that part of TEMPLATE_DIRS.
In Django 1.8 template_dirs has been deprecated and is now expected to be defined using TEMPLATES["DIRS"]
The DIRS option
Changed in Django 1.8:
This value used to be defined by the TEMPLATE_DIRS setting.
Reference https://docs.djangoproject.com/en/1.8/ref/templates/api/#loader-types
Posting this as answer, since I wasted few hours on identifying the solution.
this is my first django app and I Have received the following msg:
Page not found (404)
Request Method: GET
Request URL:
Using the URLconf defined in _3Ms.urls, Django tried these URL patterns, in this order:
^ ^$ [name='vista_principal']
^admin/doc/
^admin/
The current URL, home/, didn't match any of these.
my setting.py
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media/')
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '7th)hsx0w5mwlv+oty62w(us7&xtiw#y0&12)67ld%6y1-a)4f'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = '_3Ms.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = '_3Ms.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'apps',
)
_3Ms/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', '_3Ms.views.home', name='home'),
# url(r'^_3Ms/', include('_3Ms.foo.urls')),
url(r'^', include('apps.es.urls')), # incluye las urls de es.urls.py
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
es/urls.py
from django.conf.urls import patterns, url
urlpatterns = patterns('apps.es.view',
url(r'^$', 'home_view', name='vista_principal'),
)
es/views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
def home_view(request):
return render_to_response('es/home.html', context_instance=RequestContext(request))
You don't have a url for home/.
If you added url(r'^home/$', 'home_view', name='vista_principal'), it would have something to go to.
I am trying to load my CSS, images, and javascript into my Django template using
{{ STATIC_URL }}
I am having a problem getting it to work. Here is the relevant code:
Url's.py:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
...
urlpatterns += staticfiles_urlpatterns()
Settings.py
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
MEDIA_URL = '/assets/'
STATIC_ROOT = os.path.realpath(os.path.join(PROJECT_ROOT, 'static'))
STATIC_URL = '/static/'
STATICFILES_DIRS = (
"/Users/Chris/project/static/",
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
Stylesheet URl:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css">
If you need anymore information just ask, and thanks for your help!
UPDATE:
I have added the following things trying to fix the problem. But it still persists:
To the views where I'm trying to import the stylesheet:
'context_instance':RequestContext(request),
To the setting.py file:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages",
)
Here is my Installed App's if this helps:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'djblog',
)
My URLs.py file for the admin, and pointing to my other URL file:
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'blog.views.home', name='home'),
# url(r'^blog/', include('blog.foo.urls')),
url(r'^admin/', include(admin.site.urls)),
(r'^', include('djblog.urls')),
)
My main URL file:
from django.conf.urls.defaults import *
from views import *
from models import *
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = patterns('',
(r'^$', list),
(r'^archive/(?P<archive>\d{1,2})/$', list),
(r'^\d{4}/\d{1,2}/(?P<sl>.*)/$', detail),
(r'^(?P<year>\d{4})/(?P<month>\d{1,2})/$', month),
(r'^(?P<year>\d{4})/$', year),
(r'^category/$', category),
(r'^category/(?P<category>.*)/$', one_category),
(r'^tag/$', tag),
(r'^tag/(?P<tag>.*)/$', one_tag),
)
urlpatterns += staticfiles_urlpatterns()
I have solved my own question. With the help of Kay Zhu
In my views I was passing the "context_instance" keyword argument to render_to_response, wrong.
Here is an example of the correct usage of context_instance:
def one_tag(request, tag):
#http://site_name/tag/tag_name
posts = Post.objects.order_by('-published').filter(tags__name=tag.lower())
return render_to_response('blog/one_tag.html',
{'posts':posts, 'tag':tag,},
context_instance=RequestContext(request))
This might also solve your similar problem. Add a file to your program directory with the following code:
def media_url(request):
from django.conf import settings
return {'media_url': settings.MEDIA_URL}
And this blog post has a lot of good information: http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/
Be wary though, its from 2006 :)
Using python 2.7, django 1.4.1, filebrowser 3.5.0, grappelli 2.4.2, win7 x64
So heres my problem:
Im creating a object, and trying to attach an image to it:
Clicking on search:
Navigating through folders to get to my file, and picking it:
After i pick it, this is the path it returns:
Attaching model itself:
class EntryManager(models.Manager):
def active(self):
return super(EntryManager, self).get_query_set().filter(is_active=True)
class Services(models.Model):
name = models.CharField(max_length = 20, help_text = 'Nazwa oferowanej usługi', verbose_name='Usługa')
slug = models.SlugField(max_length=255, help_text = 'Odnośnik, generowany automatycznie na podstawie nazwy', unique=True,verbose_name='Odnośnik')
icon = FileBrowseField(verbose_name='Ikona', max_length=255, directory="images/", extensions=[".jpg",'.png','.gif'], blank=True, null=True,help_text = '.jpg, .png, .gif')
is_active = models.BooleanField(help_text='Zaznacz aby obiekt był widoczny dla użytkowników', default=False)
objects = EntryManager()
class Meta:
ordering = ['name']
verbose_name = "Usługę"
verbose_name_plural = "Usługi"
def __str__(self):
return self.name
def __unicode__(self):
return self.name
def get_absolute_url(self):
return '/uslugi/%s/' % self.slug
I have no idea where to search for a problem at the moment, could any1 help?
edit:
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from filebrowser.sites import site
#when on dev, serve media files
from django.conf import settings
urlpatterns = patterns('',
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/filebrowser/', include(site.urls)),
url(r'^uslugi/?$', 'services.views.services'),
)
#when on dev, serve media files
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
and part of settings.py
import os
PROJECT_DIR = os.path.abspath(os.path.dirname(__file__) + "../../")
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'site_media/media')
STATIC_ROOT = os.path.join(PROJECT_DIR, 'site_media/static')
ADMIN_MEDIA_PREFIX = os.path.join(PROJECT_DIR, 'site_media/admin_media')
INSTALLED_APPS = (
'grappelli',
'filebrowser',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'services'
)
After reading yours urls.py I need to show You Documentation:
In your url.py import the default FileBrowser site:
from filebrowser.sites import site
and add the following URL-patterns (before any admin-urls):
urlpatterns = patterns('',
url(r'^admin/filebrowser/', include(site.urls)),
)
So only differences between You and my new project are:
I'm using Linux Ubuntu x86 on VirtualBox undex Windows 7
I have /admin/file-browser BEFORE any admin-urls:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from filebrowser.sites import site
from django.conf.urls.static import static
from django.conf import settings
admin.autodiscover()
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + patterns('',
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/filebrowser/', include(site.urls)),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^', include('django.contrib.flatpages.urls')),
)