Python Daily
2.57K subscribers
1.48K photos
53 videos
2 files
38.9K links
Daily Python News
Question, Tips and Tricks, Best Practices on Python Programming Language
Find more reddit channels over at @r_channels
Download Telegram
Blog tutorial in Django 1.10

Hello friends! Happy New Year!

I am new to Django and I am seeking your support. I'm trying to build a pretty complex website with a blog section. I've tried numerous tutorials on YouTube and the documentation and I've ended up frustrated because either the tutorial doesn't really cover everything or I'm running into compatibility issues (Django 1.9 vs Django 1.10) which I couldn't figure out. These two do not really cut it:

https://www.youtube.com/watch?v=FNQxxpM1yOs&list=PLQVvvaa0QuDeA05ZouE4OzDYLHY-XH-Nd

https://www.youtube.com/watch?v=yfgsklK_yFo&list=PLEsfXFp6DpzQFqfCur9CJ4QnKQTVXUsRy

Could someone please point me to a full in depth Django 1.10 tutorial or some kind of template? I've pretty good at the Front End and I just want to get my first webapp off the ground.

Much appreciated

/r/django
https://redd.it/5lk67y
URL not appearing in DRF router!

I have all these router url's set up, but when I add search it doesn't work!
router.register(r'search', search_api.SearchViewSet, base_name='search-api')

i've narrowed it down to when i swap out where the view goes (search_api.SearchViewSet), then it shows up on the django 404 page.... I've tried many combinations of views and nothing makes it work! Why could this be. For example, my current view is :

class SearchViewSet(viewsets.ViewSet):
queryset = Data.objects.all()
renderer_classes = (JSONRenderer, )
def get(self, request, format=None):
print('test')
return Response({'test': 1})


/r/django
https://redd.it/5knjfe
Django or flask?

I am completely inexperienced these libraries. I wanted to see it it'd be feasible to build a site that would display some matplotlib graphs and pandas dataframes. Ideally, these dataframes could be filtered or sorted and exported. The underlying raw data would be refreshed every 30 minutes. Someone could visit and see overall performance and then customize their view.

Another big use case for me would be to allow people to update some "custom" dimension tables and to let me know when certain dimensions are expired or recycled. Right now this is done through csv files being overwritten on an sftp site. It'd be nice to have a front end.

My workflow is centered around using a few libraries to gather external data from SFTP sites, shared folders, and even web sites with selenium. I then read this data with pandas, do my formatting and cleaning, etc, and then I use psycopg2 COPY command to send the data to Postgres. Ultimately, his external data (all different formats and sources) comes together into internal reports.

Some of the data is used for reporting which is sent out through emails (attachments and to_html with pandas to display a table), tableau, and to various shared folders and sftp sites. I'd like to test having some of this on a website instead.

/r/Python
https://redd.it/5lk0or
How to Activate/Deactivate virtualenv on linux with subprocess.Popen?

I achieved to create and to activate the virtualenv on Linux but I cannot deactivate it.
The deactivate command is not available through subprocess.Popen even if shell argument is set to True.

Do you have any ideas?

/r/Python
https://redd.it/5lift9
[Question] I learnt java in high school. How I proceed with learning python?

I'm familiar with object oriented programming and other basic high school stuff. How do I start learning python and other languages?

/r/Python
https://redd.it/5lku9c
I made a small script for looking up word definitions

I've been reading a lot of old texts in school lately which meant I had to keep looking up old words, I noticed that the results almost always showed up in the first page of a google search and decided to try and automate the process.

The script use requests and beautiful soup to send a http search request to google, and then parse through the resulting html fetching any link which domain has a section in config.ini with a css selector for the desired content (the definition of the words).

The script then loops over all the links, extracting the content defined by the css selector in config.ini and displays it in the command line.

I don't know if this is that interesting to this sub, but I thinks is kind of cool and makes my life easier, so I decided to share it in case someone is in the same boat.

[GitHub Link](https://github.com/nikolajlauridsen/WordSearch)

/r/Python
https://redd.it/5lkvq2
User in class based view

Hi guys, im working in first project with django and i have to prepare for an exam. I ll have to make forms and views to create a register with "normal" views and class based views. It´s easy to do but i dont know how to set automatically de foreign key qhen i work with class based views. This foreign key has to be the User that is authentified.

When i work with simple views I get him using:
user_foreign=get_object_or_404(User, username=request.user.get_username())

When i work with class based views i dont know how to do it, can u help me?
Thanks a lot.

/r/django
https://redd.it/5lkmq0
Django admin giving 500 error on local server

I just started this app. I have a single view I was trying to write, that does work. I just tried to reach the django admin and got a 500 error. What is going on here?

main urls.py
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^account/', include('account.urls')),
]

account/views.py
from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth import authenticate, login
from .forms import LoginForm


# Create your views here.


def user_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(username=cd['username'],
password=cd['password'])
if user is not None:
if user.is_active:
login(request, user)
return HttpResponse('Authenticated ' \
'successfully')
else:
return HttpResponse('Disabled account')
else:
return HttpResponse('Invalid login')
else:
form = LoginForm()
return render(request, 'account/login.html', {'form': form})

account/urls.py
from django.conf.urls import url
from . import views

urlpatterns = {
# post views
url(r'^login/$', views.user_login, name='login'),
}

error
Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/admin/

Django Version: 1.8.6
Python Version: 3.5.2
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'account')
Installed Middleware:
('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',
'django.middleware.security.SecurityMiddleware')


Traceback:
File "/home/swapnil/python_envs/bookmarks/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/swapnil/python_envs/bookmarks/lib/python3.5/site-packages/django/contrib/admin/sites.py" in wrapper
254. return self.admin_view(view, cacheable)(*args, **kwargs)
File "/home/swapnil/python_envs/bookmarks/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view
110. response = view_func(request, *args, **kwargs)
File "/home/swapnil/python_envs/bookmarks/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/home/swapnil/python_envs/bookmarks/lib/python3.5/site-packages/django/contrib/admin/sites.py" in inner
233. return view(request, *args, **kwargs)
File "/home/swapnil/python_envs/bookmarks/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/home/swapnil/python_envs/bookmarks/lib/python3.5/site-packages/django/contrib/admin/sites.py" in index
421. model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name)
File "/home/swapnil/python_envs/bookmarks/lib/python3.5/s
ite-packages/django/core/urlresolvers.py" in reverse
549. app_list = resolver.app_dict[ns]
File "/home/swapnil/python_envs/bookmarks/lib/python3.5/site-packages/django/core/urlresolvers.py" in app_dict
351. self._populate()
File "/home/swapnil/python_envs/bookmarks/lib/python3.5/site-packages/django/core/urlresolvers.py" in _populate
307. for name in pattern.reverse_dict:
File "/home/swapnil/python_envs/bookmarks/lib/python3.5/site-packages/django/core/urlresolvers.py" in reverse_dict
337. self._populate()
File "/home/swapnil/python_envs/bookmarks/lib/python3.5/site-packages/django/core/urlresolvers.py" in _populate
284. for pattern in reversed(self.url_patterns):

Exception Type: TypeError at /admin/
Exception Value: argument to reversed() must be a sequence


/r/djangolearning
https://redd.it/5kzsn6
py3redirect 1.1 (Chrome extension) - automatically redirects to Python 3 documentation when Python 2 docs page is requested

/u/yaph has posted a link to this Chrome extension some time ago. I am an author of this and recently updated the py3redirect to 1.1, which brings cache (so the extension can redirect immediately if it already knows py3 doc exists for given page) and a button for temporarily disabling redirecting. This version should also fixes the problem with back button - which caused the browser to reload the page (i.e. back to py2 docs, which were immediately redirected to py3), instead of actually going back.

I saw that some people appreciated this however simple work, so I hope you'll enjoy some improvements I made. If you have any other suggestions, that will be appreciated by me. :)

https://chrome.google.com/webstore/detail/py3redirect/codfjigcljdnlklcaopdciclmmdandig

/r/Python
https://redd.it/5ll06t
Last user activity

Django's user model has a last_login field. However most of my users don't log out. I understand there a multiple ways to track latest user activity. What do you guys recommend? [Preferable a method that is compatible with Python 3 and Django 1.9]

/r/django
https://redd.it/5ln4ak
Year of Programming Challenge!

Hello all, there was a post over at r/learnprogramming, it was a thread about people wanting to code everyday for this year. the community outgrew the groupme chat, and grew into a slack channel where we are sitting at 300+ members, and have 60 people forked the github repository. I thought it was a super cool idea and wanted to share it with people over here who wanted to sharpen their python programming skills!

A github organization was created where challenges can be posted and people can submit pull-requests and get their work merged with the organizations master repository. this is amazing as it will help keep our skills sharp, and start to build a github reputation thatll look good to recruiters.


heres the slack channel: https://yearofprogramming.slack.com/shared_invite/MTIyNDM3Mjc1OTI1LTE0ODMzMDQwMzAtOGNkNTA2NDY5Yg


and the github org repo: https://github.com/YearOfProgramming/2017Challenges

/r/Python
https://redd.it/5lnxtp
Trying to make my own version of django-admin startproject. Have I created a monster?

I'm currently learning Django, specifically how to create a new project. I was taught to use the command
django-admin startproject {project name}
in bash and then modify some of the files it created. I thought that modifying the same files in the same way every time I made a new Django project was inefficient, so I wrote a shell script that would create the files for me, already modified to how they needed to be.

It seemed like a good idea at the time, but now I'm getting a whole bunch of errors I don't understand. Have I created a monster I can no longer control? Any help is appreciated.

Here is my shell script:
new_django.sh

# Activate Django Virtual Envirnoment
source ~/Desktop/PYTHON/myEnvironments/djangoEnv/bin/activate

# Get names of project and app
echo "Enter project name:"
read project_name
echo "Enter application name:"
read app_name
echo "Copy the following string to be used as a secret key:"
python ~/Desktop/PYTHON/Django/secret_key.py
read secret_key

# Create Django Project
mkdir $project_name
cd $project_name

touch manage.py
echo "#!/usr/bin/env python\nimport os\nimport sys\n\nif __name__ == \"__main__\":\n\tos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"$project_name.settings\")\n\ttry:\n\t\tfrom django.core.management import execute_from_command_line\n\texcept ImportError:\n\t\t# The above import may fail for some other reason. Ensure that the\n\t\t# issue is really that Django is missing to avoid masking other\n\t\t# exceptions on Python 2.\n\t\ttry:\n\t\t\timport django\n\t\texcept ImportError:\n\t\t\traise ImportError(\n\t\t\t\t\"Couldn't import Django. Are you sure it's installed and \"\n\t\t\t\t\"available on your PYTHONPATH environment variable? Did you \"\n\t\t\t\t\"forget to activate a virtual environment?\"\n\t\t\t)\n\t\traise\n\texecute_from_command_line(sys.argv)\n" >> manage.py

touch db.sqlite3
echo -n -e "\x53\x51\x4c\x69\x74\x65\x20\x66\x6f\x72\x6d\x61\x74\x20\x33\x00\x10\x00\x01\x01\x00\x40\x20\x20\x00\x00\x00\x01\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00..." >> db.sqlite3

mkdir $project_name
cd $project_name

touch __init__.py

touch settings.py
echo "\"\"\"\nDjango settings for $project_name project.\n\nGenerated by 'new_django.sh' using Django 1.10.3.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.10/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.10/ref/settings/\n\"\"\"\n\nimport os\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '$secret_key'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = [\n\t'apps.$app_name',\n\t'django.contrib.admin',\n\t'django.contrib.auth',\n\t'django.contrib.contenttypes',\n\t'django.contrib.sessions',\n\t'django.contrib.messages',\n\t'django.contrib.staticfiles',\n]\n\nMIDDLEWARE = [\n\t'django.middleware.security.SecurityMiddleware',\n\t'django.contrib.sessions.middleware.SessionMiddleware',\n\t'django.middleware.common.CommonMiddleware',\n\t'django.middleware.csrf.CsrfViewMiddleware',\n\t'django.contrib.auth.middleware.AuthenticationMiddleware',\n\t'django.contrib.messages.middleware.MessageMiddleware',\n\t'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = '$project_name.urls'\n\nTEMPLATES = [\n\t{\n\t\t'BACKEND': 'django.template.backends.django.Django
Templates',\n\t\t'DIRS': [],\n\t\t'APP_DIRS': True,\n\t\t'OPTIONS': {\n\t\t\t'context_processors': [\n\t\t\t\t'django.template.context_processors.debug',\n\t\t\t\t'django.template.context_processors.request',\n\t\t\t\t'django.contrib.auth.context_processors.auth',\n\t\t\t\t'django.contrib.messages.context_processors.messages',\n\t\t\t],\n\t\t},\n\t},\n]\n\nWSGI_APPLICATION = '$project_name.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.10/ref/settings/#databases\n\nDATABASES = {\n\t'default': {\n\t\t'ENGINE': 'django.db.backends.sqlite3',\n\t\t'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n\t}\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n\t{\n\t\t'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n\t},\n\t{\n\t\t'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n\t},\n\t{\n\t\t'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n\t},\n\t{\n\t\t'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n\t},\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.10/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.10/howto/static-files/\n\nSTATIC_URL = '/static/'\n\n" >> settings.py

touch urls.py
echo "\"\"\"$project_name URL Configuration\n\nThe \`urlpatterns\` list routes URLs to views. For more information please see:\n\thttps://docs.djangoproject.com/en/1.10/topics/http/urls/\nExamples:\nFunction views\n\t1. Add an import: from my_app import views\n\t2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n\t1. Add an import: from other_app.views import Home\n\t2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n\t1. Import the include() function: from django.conf.urls import url, include\n\t2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\n# from django.contrib import admin\n\nurlpatterns = [\n\turl(r'^', include('apps.$app_name.urls')),\n]" >> urls.py

touch wsgi.py
echo "\"\"\"\nWSGI config for $project_name project.\n\nIt exposes the WSGI callable as a module-level variable named \`\`application\`\`.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/\n\"\"\"\n\nimport os\n\nfrom django.core.wsgi import get_wsgi_application\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"$project_name.settings\")\n\napplication = get_wsgi_application()\n" >> wsgi.py

cd ..

mkdir apps
cd apps

touch __init__.py

mkdir $app_name
cd $app_name

touch __init__.py

touch admin.py
echo "from django.contrib import admin\n\n# Register your models here.\n" >> admin.py

touch apps.py
echo "from __future__ import unicode_literals\n\nfrom django.apps import AppConfig\n\n\nclass AppNameConfig(AppConfig):\n\tname = '$app_name'\n\n" >> apps.py

mkdir migrations
cd migrations

touch __init__.py

cd ..

touch models.py
echo "from __future__ import unicode_literals\n\nfrom django.db import models\n\n# Create your models here.\n" >> models.py

mkdir templates
cd templates

mkdir $app_name
cd $app_name

touch index.html
echo "<!DOCTYPE html>\n<html>\n\t<head>\n\t\t<title>$project_name</title>\n\t</head>\n\t<body>\n\t\t<h1>$app_name</h1>\n\t</body>\n</html>\n" >> index.html

cd ..

cd ..
touch tests.py
echo "from django.test import TestCase\n\n# Create your tests here.\n" >> tests.py

touch urls.py
echo "from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n\turl(r'^.*$', views.index),\n]\n" >> urls.py

touch views.py
echo "from django.shortcuts import render\n\n# Create your views here.\n\ndef index(request):\n\treturn render(request,\"$app_name/index.html\")\n" >> views.py

cd ..

cd ..

# python manage.py migrate

# echo "Application $app_name created in $project_name"

And here are the errors I'm getting:

Enter project name:
lemon
Enter application name:
tiger
Copy the following string to be used as a secret key:
052cif$=_$043%ffntthkm@-n*evj6wtre64xk@_sgv1fjirr@
052cif$=_$043%ffntthkm@-n*evj6wtre64xk@_sgv1fjirr@
(djangoEnv) JesusIsMyZolofts-MacBook-Pro:test JesusIsMyZoloft$ cd lemon
(djangoEnv) JesusIsMyZolofts-MacBook-Pro:lemon JesusIsMyZoloft$ python manage.py migrate
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute
output = self.handle(*args, **options)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 83, in handle
executor = MigrationExecutor(connection, self.migration_progress_callback)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/migrations/executor.py", line 20, in __init__
self.loader = MigrationLoader(self.connection)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/migrations/loader.py", line 52, in __init__
self.build_graph()
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/migrations/loader.py", line 203, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations
self.ensure_schema()
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema
if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()):
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/backends/base/introspection.py", line 57, in table_names
return get_names(cursor)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/backends/base/introspection.py", line 52, in get_names
return sorted(ti.name for ti in self.get_table_list(cursor)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/backends/sqlite3/introspection.py", line 68, in get_table_list
ORDER BY name""")
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/m