Django1.11 - Show media on localhost - django-media

I'm having hard time to display media on local system.. the problem is that:
{{ producer.img.url }}
gives me a url path relative to the page I'm browsing, so it always fails to locate the file. It actually prints something like:
media/media/djprofiles/john_0VtCrdA.jpg
which obviously fails (note the missing initial "/").
Following Django docs, I added in my urls.py:
urlpatterns = [
url(r'^i18n/', include('django.conf.urls.i18n')),
]
urlpatterns += i18n_patterns(
...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and settings.py is as follow:
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = 'media/'
The img field is defined in models.py as follow:
img = models.ImageField(upload_to=settings.MEDIA_URL + 'djprofiles')
I know there are already many questions relative to showing media on local system, but none seems to provide me with a working solution.

did you try
MEDIA_URL = '/media/'
in settings.py?

Related

How to limit url parameters in Django REST Framework's Router to ints?

When I have an urls.py file like this:
# urls.py
router = SimpleRouter(trailing_slash=False)
router.register("/?", MembersController, basename="member")
urlpatterns = router.urls
Then the generated URL for the single object is (?P<pk>[^/.]+)$. I'd like for it to include the int: "converter type". Is that possible at all? Or would I have to stop using DRF's router and create my own URL patterns?
In your MembersController you can specify the '[0-9]+' as lookup_value_regex:
class MembersController(ModelViewSet):
lookup_value_regex = '[0-9]+'
# &vellip;
as default it makes use of '[^/.]+', as we can see in the source code [GitHub]:
lookup_value = getattr(viewset, 'lookup_value_regex', '[^/.]+')

How do I enable following URL capability to work in my code?

I am attempting to add the follow url capability but can't seem to get it to work. I need to crawl all the pages. There are around 108 pages of the job listings. Thank you.
import scrapy
class JobItem(scrapy.Item):
# Data structure to store the title, company name and location of the job
title = scrapy.Field()
company = scrapy.Field()
location = scrapy.Field()
class PythonDocumentationSpider(scrapy.Spider):
name = 'pydoc'
start_urls = ['https://stackoverflow.com/jobs?med=site-ui&ref=jobs-tab']
def parse(self, response):
for follow_href in response.xpath('//h2[#class="fs-body2 job-details__spaced mb4"]/a/#href'):
follow_url = response.urljoin(follow_href.extract())
yield scrapy.Request(follow_url, callback=self.parse_page_title)
for a_el in response.xpath('//div[#class="-job-summary"]'):
section = JobItem()
section['title'] = a_el.xpath('.//a[#class="s-link s-link__visited job-link"]/text()').extract()[0]
span_texts = a_el.xpath('.//div[#class="fc-black-700 fs-body1 -company"]/span/text()').extract()
section['company'] = span_texts[0]
section['location'] = span_texts[1]
print(section['location'])
#print(type(section))
yield section
I am attempting to get the following url capability to work with my code and then be able to crawl the pages and store job postings in csv file.
.extract() return a list. In most cases you'll need to use .get() or .extract_first() instead if you don't need a list.
First you need to rewrite this part:
for follow_href in response.xpath('//h2[#class="fs-body2 job-details__spaced mb4"]/a/#href').getall(): # or .extract()
follow_url = response.urljoin(follow_href)
yield scrapy.Request(follow_url, callback=self.parse_page_title)

Scrapy works in shell but spider returns empty csv

I am learning Scrapy. Now I just try to scrapy items and when I call spider:
planefinder]# scrapy crawl planefinder -o /User/spider/planefinder/pf.csv -t csv
it shows tech information and no scraped content (Crawled 0 pages .... etc), and it returns an empty csv file.
The problem is when i test xpath in scrapy shell it works:
>>> from scrapy.selector import Selector
>>> sel = Selector(response)
>>> flights = sel.xpath("//div[#class='col-md-12'][1]/div/div/table//tr")
>>> items = []
>>> for flt in flights:
... item = flt.xpath("td[1]/a/#href").extract_first()
... items.append(item)
...
>>> items
The following is my planeFinder.py code:
# -*-:coding:utf-8 -*-
from scrapy.spiders import CrawlSpider
from scrapy.selector import Selector, HtmlXPathSelector
from planefinder.items import arr_flt_Item, dep_flt_Item
class planefinder(CrawlSpider):
name = 'planefinder'
host = 'https://planefinder.net'
start_url = ['https://planefinder.net/data/airport/PEK/']
def parse(self, response):
arr_flights = response.xpath("//div[#class='col-md-12'][1]/div/div/table//tr")
dep_flights = response.xpath("//div[#class='col-md-12'][2]/div/div/table//tr")
for flight in arr_flights:
arr_item = arr_flt_Item()
arr_flt_url = flight.xpath('td[1]/a/#href').extract_first()
arr_item['arr_flt_No'] = flight.xpath('td[1]/a/text()').extract_first()
arr_item['STA'] = flight.xpath('td[2]/text()').extract_first()
arr_item['From'] = flight.xpath('td[3]/a/text()').extract_first()
arr_item['ETA'] = flight.xpath('td[4]/text()').extract_first()
yield arr_item
Please before going to CrawlSpider please check the docs for Spiders, some of the issues I've found were:
Instead of host use allowed_domains
Instead of start_url use start_urls
It seem that the page needs to have some cookies set or maybe it's using some kind of basic anti-bot protection, and you need to land somewhere else first.
Try this (I've also changed a bit :
# -*-:coding:utf-8 -*-
from scrapy import Field, Item, Request
from scrapy.spiders import CrawlSpider, Spider
class ArrivalFlightItem(Item):
arr_flt_no = Field()
arr_sta = Field()
arr_from = Field()
arr_eta = Field()
class PlaneFinder(Spider):
name = 'planefinder'
allowed_domains = ['planefinder.net']
start_urls = ['https://planefinder.net/data/airports']
def parse(self, response):
yield Request('https://planefinder.net/data/airport/PEK', callback=self.parse_flight)
def parse_flight(self, response):
flights_xpath = ('//*[contains(#class, "departure-board") and '
'./preceding-sibling::h2[contains(., "Arrivals")]]'
'//tr[not(./th) and not(./td[#class="spacer"])]')
for flight in response.xpath(flights_xpath):
arrival = ArrivalFlightItem()
arr_flt_url = flight.xpath('td[1]/a/#href').extract_first()
arrival['arr_flt_no'] = flight.xpath('td[1]/a/text()').extract_first()
arrival['arr_sta'] = flight.xpath('td[2]/text()').extract_first()
arrival['arr_from'] = flight.xpath('td[3]/a/text()').extract_first()
arrival['arr_eta'] = flight.xpath('td[4]/text()').extract_first()
yield arrival
The problem here is not understanding correctly which "Spider" to use, as Scrapy offers different custom ones.
The main one, and the one you should be using is the simple Spider and not CrawlSpider, because CrawlSpider is used for a more deep and intensive search into forums, blogs, etc.
Just change the type of spider to:
from scrapy import Spider
class plane finder(Spider):
...
Check the value of ROBOTSTXT_OBEY in your settings.py file. By default it's set to True (but not when you run shell). Set it to False if you wan't to disobey robots.txt file.

Dajaxice. Cannot call method '...' of undefined. Again

I'm stuck in trying to create a simplest application with dajaxice.
I'n read all topics about this problem here and not only here, rewrite all code many times, but still do not see what the problem is.
the most interesting that, these examples are working (almost all):
https://github.com/jorgebastida/django-dajaxice/downloads dajaxice-examples.tar.gz
But in my project i have this:
Uncaught TypeError: Cannot call method 'sayhello' of undefined
my tools:
Windows 7 64
python-2.7.3
Django-1.4.2
django-dajaxice-0.2
project structure:
BlocalProject/
templates/
template_1.html
manage.py
BlocalProject/
ajapp/
__init__.py
ajview.py
__init__.py
settings.py
urls.py
views.py
wsgi.py
urls.py:
from django.conf.urls.defaults import *
import settings
from dajaxice.core import dajaxice_autodiscover
dajaxice_autodiscover()
urlpatterns = patterns('',
(r'^%s/' % (settings.DAJAXICE_MEDIA_PREFIX), include('dajaxice.urls')),
(r'^$', 'BlocalProject.views.start_page'),
)
views.py:
from django.shortcuts import render
def start_page(request):
return render(request,'template_1.html')
ajapp.py:
from django.utils import simplejson
from dajaxice.core import dajaxice_functions
def sayhello(request):
return simplejson.dumps({'message': 'Trololo!'})
dajaxice_functions.register(sayhello)
template_1.html:
{% load dajaxice_templatetags %}
<html>
{% dajaxice_js_import %}
<script>
function alertMessage(data){
alert(data.message);
return false;
}
</script>
<body>
Some text
<input type="button" value="Get!" onclick="Dajaxice.ajapp.sayhello(alertMessage);" />
</body>
</html>
settings.py:
# Django settings for BlocalProject project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = '' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = '' # Or path to database file if using sqlite3.
DATABASE_USER = '' # Not used with sqlite3.
DATABASE_PASSWORD = '' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = ')er9!%4v0=nmxd#2=j1*tlktmidq8aam2y)-%fjf6%^xp*5r)c'
# 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.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'BlocalProject.urls'
# Python dotted path to the WSGI application used by Django's runserver.
#WSGI_APPLICATION = 'BlocalProject.wsgi.application'
TEMPLATE_DIRS = (
'D:/_/Site_test/Djpr/BlocalProject/templates',
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
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.core.context_processors.request",
"django.contrib.messages.context_processors.messages",)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'dajaxice',
'BlocalProject.ajapp',
)
DAJAXICE_MEDIA_PREFIX = "dajaxice"
DAJAXICE_DEBUG = True
DAJAXICE_JS_DOCSTRINGS = True
#DAJAXICE_NOTIFY_EXCEPTIONS = True
import logging
logging.basicConfig(level=logging.DEBUG)
This might be too late, but...
IMHO, the dajaxice_autodiscover() doesn't actually get your method. I remember having a similar problem with another ajax lib and I've solved it by adding an import in the models.py (or views.py), which get imported when the app starts. The example you mention has an import in simple/views.py:
# Create your views here.
from django.shortcuts import render
# THIS ONE!
from dajaxice.core import dajaxice_functions
# ---------
def index(request):
return render(request, 'simple/index.html')
which looks like it's initialising stuff. My approach would be:
put a couple of print statements in your ajapp.py and see if they get printed out.
create empty models.py and views.py in your BlocalProject.ajapp (does django still use models.py to validate a module as a django app?)
If your print statements don't get triggered, then you need to find out why. As I mentioned, it might be as simple as importing your ajax module in models :)

Is there an easy way of referring to the public directory in Sinatra?

Imagine this structure:
/project
/templates
view1.haml
view2.haml
misc_views/
view3.haml
view4.haml
even_deeper/
view5.haml
/public
script1.js
The depth of the templates can vary, and I would like to refer to the public directory if I want to include some files from it. Is there a helper or some other gimmick that takes me to the public directory? It seems bad to have something like ../../../public/script1.js , or ../../public/script1.js in my views. Surely there must be a better way.
You can use the settings.public configuration to refer to the public directory. For example:
get "/" do
js = File.join( settings.public, 'script1.js' )
File.exists?( js ) #=> true
end
As this is an absolute path, there is no need to make it relative to your view to get the file. You could reach out to this from your view, but I would personally set the path as an instance variable from the controller.
get "/" do
# If you really only need the directory
#public = settings.public
# If you actually need the path to a specific file
#main = File.join( settings.public, 'main.js' )
# If you actually need the contents of a file
#js = IO.read( File.join( settings.public, 'main.js' ) )
end
You must include the static resources by the root of the web address or a relative request path, as it will be the browser who requests it, not your server-side code. Unless I am mistaken in your case?
<script type="text/javascript" src="/script1.js"></script>

Resources