Coder Social home page Coder Social logo

examples's Introduction

Lightweight Django Code Examples

This repository contains all the code from the book, Lightweight Django by Julia Elman and Mark Lavin.

Using These Examples

Each example has been separated out into different branches that correspond to their chapter. Below you will find links to each chapters example code:

Terms & Conditions

These code examples are excerpted from Lightweight Django by Julia Elman and Mark Lavin published by O’Reilly Media, Inc. (ISBN 9781491945940) which you can purchase here: http://shop.oreilly.com/product/0636920032502.do. You may use these code examples in your programs and documentation. You do not need to contact O'Reilly for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of this example code does not require permission. Selling or distributing a set of examples from O'Reilly books does require permission. Answering a question by citing the book and quoting example code does not require permission. Incorporating a significant amount of this example code into your product’s documentation does require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Lightweight Django by Julia Elman and Mark Lavin (O’Reilly). Copyright 2014 Julia Elman and Mark Lavin. 978-1-4919-4594-0.”

If you feel your use of these code examples falls outside fair use or the permission given here, feel free to contact O'Reilly at [email protected]

examples's People

Contributors

mlavin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

examples's Issues

Reusable Template creation failing

First of all, great book (so far).

When I use the command suggested in the book:

django-admin.py startproject foo --template=project_name

I get the following error message (even when I download your code example):
CommandError: couldn't handle project template project_name.

Thanks in advance,
João.

Issue with Chapter 4 source.

I got this exception when i use exact code of Chapter 4:

Meta.fields contains a field that isn't defined on this FilterSet

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000000003F05D90>
Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "C:\Python34\lib\site-packages\django\core\management\commands\runserver.py", line 116, in inner_run
    self.check(display_num_errors=True)
  File "C:\Python34\lib\site-packages\django\core\management\base.py", line 426, in check
    include_deployment_checks=include_deployment_checks,
  File "C:\Python34\lib\site-packages\django\core\checks\registry.py", line 75, in run_checks
    new_errors = check(app_configs=app_configs)
  File "C:\Python34\lib\site-packages\django\core\checks\urls.py", line 10, in check_url_config
    return check_resolver(resolver)
  File "C:\Python34\lib\site-packages\django\core\checks\urls.py", line 19, in check_resolver
    for pattern in resolver.url_patterns:
  File "C:\Python34\lib\site-packages\django\utils\functional.py", line 33, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Python34\lib\site-packages\django\core\urlresolvers.py", line 417, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "C:\Python34\lib\site-packages\django\utils\functional.py", line 33, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Python34\lib\site-packages\django\core\urlresolvers.py", line 410, in urlconf_module
    return import_module(self.urlconf_name)
  File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 1129, in _exec
  File "<frozen importlib._bootstrap>", line 1471, in exec_module
  File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
  File "C:\Users\Saket\PycharmProjects\api34\api34\urls.py", line 20, in <module>
    from board.urls import router
  File "C:\Users\Saket\PycharmProjects\api34\board\urls.py", line 3, in <module>
    from . import views
  File "C:\Users\Saket\PycharmProjects\api34\board\views.py", line 5, in <module>
    from .forms import SprintFilter, TaskFilter
  File "C:\Users\Saket\PycharmProjects\api34\board\forms.py", line 29, in <module>
    class TaskFilter(django_filters.FilterSet):
  File "C:\Python34\lib\site-packages\django_filters\filterset.py", line 182, in __new__
    raise TypeError("Meta.fields contains a field that isn't defined "
TypeError: Meta.fields contains a field that isn't defined on this FilterSet

when i remove assigned from this line-
fields = ('sprint', 'status', 'assigned', 'backlog', )

server run the project, Sprint & Users urls works fine and task url show me error.
So there must be something wrong with this assigned keyword in that particular Line of code.

Help me with this error. Thanx in Advance

scrum: validate_end() missing 1 required positional argument: 'source'

After fixing error:

It is redundant to specify `get_links` on SerializerMethodField 'links' in serializer 'SprintSerializer',
because it is the same as the default method name. Remove the `method_name` argument.

in class SprintSerializer and TaskSerializer with links, status_display fields I got stuck with this error:

TypeError at /api/sprints/
validate_end() missing 1 required positional argument: 'source'
Request Method: POST
Request URL:    http://localhost:8000/api/sprints/
Django Version: 1.7.1
Exception Type: TypeError
Exception Value:    validate_end() missing 1 required positional argument: 'source'
Exception Location: /home/dade/.virtuaenvs/kikiri-test/lib/python3.4/site-packages/rest_framework/serializers.py in to_internal_value, line 362
Python Executable:  /home/dade/.virtuaenvs/kikiri-test/bin/python
Python Version: 3.4.0
Python Path:    
['/home/dade/projects/python/kikiri-test-django/scrum',
 '/home/dade/.virtuaenvs/kikiri-test/lib/python3.4',
 '/home/dade/.virtuaenvs/kikiri-test/lib/python3.4/plat-x86_64-linux-gnu',
 '/home/dade/.virtuaenvs/kikiri-test/lib/python3.4/lib-dynload',
 '/usr/lib/python3.4',
 '/usr/lib/python3.4/plat-x86_64-linux-gnu',
 '/home/dade/.virtuaenvs/kikiri-test/lib/python3.4/site-packages']
Server time:    Thu, 18 Dec 2014 02:16:36 +0000

this happens when I try to post a sprint with due date set to 01/12/2014. Firstly I thought this was my type error but after cloning examples got the same error.

Problem when update to redis.

 onmessage: function (message) {
var result = JSON.parse(message.data);
this.trigger('message', result, message);
if (result.model && result.action) {
this.trigger(result.model + ':' + result.action,
result.id, result, message);
}
},

onmessage function still use, result.model. But in watercooler. Message format have been changed to:

 message = json.dumps({
'sender': sender and sender.uid,
'message': message
})

So it can't trigger onmessage/

Gunicorn (Windows)

Unfortunately the 'fcntl' module necessary to run the command gunicorn hello --log-file=- isn't available on Windows. However, I don't think this affects the rest of Gunicorn's functionality with chapter one.

Error using Requests to PUT task status

So, trying to follow along with Chapter 6, I hit the API via requests:

import requests
import datetime
response = requests.get('http://localhost:9000/api/tasks', auth=('admin', 'admin'))
tasks = response.json()
t0 = tasks['results'][0]
t0['assigned'] = 'admin'
t0['status'] = 2
today = datetime.date.today()
t0['started'] = today
response = requests.put(t0['links']['self'], data=t0, auth=('admin', 'admin'))

But when I PUT the task back, I'm met with a 400 response:

In [21]: response = requests.put(t0['links']['self'], data=t0, auth=('admin', 'admin'))
In [22]: response.text
Out[22]: u'{"non_field_errors":["Backlog tasks must have \\"Not Started\\" status."]}'

I'm also a bit confused, and perhaps this is related, about the statuses as defined in the models versus in the Backbone UI:

In [27]: from board import models
In [28]: models.Task.STATUS_TODO
Out[28]: 1

Whereas when I hit up http://localhost:9000/#sprint/1, I see five statuses:
Backlog, Not Started, In Development, In Testing, Completed

I haven't dug too far down yet, but it seems like there's a conflict in the STATUS codes:
https://github.com/lightweightdjango/examples/blob/chapter-6/scrum/board/static/board/js/views.js#L307

            this.statuses = {
                unassigned: new StatusView({
                    sprint: null, status: 1, title: 'Backlog'}),
                todo: new StatusView({
                    sprint: this.sprintId, status: 1, title: 'Not Started'}),
                active: new StatusView({
                    sprint: this.sprintId, status: 2, title: 'In Development'}),
                testing: new StatusView({
                    sprint: this.sprintId, status: 3, title: 'In Testing'}),
                done: new StatusView({
                    sprint: this.sprintId, status: 4, title: 'Completed'})
            };

versus
https://github.com/lightweightdjango/examples/blob/chapter-6/scrum/board/models.py#L20

    STATUS_TODO = 1
    STATUS_IN_PROGRESS = 2
    STATUS_TESTING = 3
    STATUS_DONE = 4

    STATUS_CHOICES = (
        (STATUS_TODO, _('Not Started')),
        (STATUS_IN_PROGRESS, _('In Progress')),
        (STATUS_TESTING, _('Testing')),
        (STATUS_DONE, _('Done')),
    )

Xhr responseJSON Property

The standard XMLHttpRequest has no responseJSON property. So in this file:
views.js

 failure: function (xhr, status, error) {
var errors = xhr.responseJSON;
this.showErrors(errors);
}

must be change to
var errors = JSON.parse(xhr.responseText);

Issue with Chapter 4 source.

I downloaded the source code from this site and only changed the database from PostgreSQL to sqllite3, mainly because I didn't feel like bothering with installing yet another db on my machine. So don't know if that cause the error.

When I tried clicking on a task I got the following error:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/api/tasks/

Django Version: 1.7.5
Python Version: 2.7.9
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'board')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')


Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
57.         return view_func(*args, **kwargs)
File "C:\Python27\lib\site-packages\rest_framework\viewsets.py" in view
85.             return self.dispatch(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch
407.             response = self.handle_exception(exc)
File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch
404.             response = handler(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\rest_framework\mixins.py" in list
40.         instance = self.filter_queryset(self.get_queryset())
File "C:\Python27\lib\site-packages\rest_framework\generics.py" in filter_queryset
144.             queryset = backend().filter_queryset(self.request, queryset, self)
File "C:\Python27\lib\site-packages\rest_framework\filters.py" in filter_queryset
68.             return filter_class(request.query_params, queryset=queryset).qs
File "C:\Users\WindozeUser\django\examples-chapter-4\examples-chapter-4\scrum\board\forms.py" in __init__
39.         super().__init__(*args, **kwargs)

Exception Type: TypeError at /api/tasks/
Exception Value: super() takes at least 1 argument (0 given)

I corrected the section of code (line 39) in board/forms.py by changing:

 super().__init__(*args, **kwargs)

to:

super(TaskFilter, self).__init__(*args, **kwargs)

which worked for me to resolve the issue.

I came to this solution from following the last answer at http://stackoverflow.com/questions/10838596/python-class-super-variable.

I'm very new to both Python and Django/Django REST.

checked out chapter 6 and couldn't get it working

After spending a lot of time matching my code with the book and this repo (not quite identical) I just checked out chapter 6 and couldn't get it working. Honestly, I haven't read the whole chapter, as I started following the repo once I couldn't get the sprints to show up by the first live example (section "Using the Client State").

Anyway, I got a 500 error when posting to api/tasks.

It's been going just great up until now. Is this just me? I'll dig a little deeper, but this is my first time using backbone, so it's all a little foggy.

Thanks,
Ben

Creating sprint using python requests library demo code not working

This is what I get as I follow along the python requests example:

PS C:\Users\WindozeUser\Desktop\django\chapter-4\scrum> C:\Python34\python.exe
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> import pprint
>>> response = requests.get('http://localhost:8000/api/')
>>> response.status_code
200
>>> api = response.json()
>>> pprint.pprint(api)
{'sprints': 'http://localhost:8000/api/sprints/',
'tasks': 'http://localhost:8000/api/tasks/',
'users': 'http://localhost:8000/api/users/'}
>>> response.status_code
200
>>> response = requests.get(api['sprints'], auth=('demo','test'))
>>> response.status_code
200
>>> import datetime
>>> today = datetime.date.today()
>>> two_weeks = datetime.timedelta(days=14)
>>> data = {'name': 'Current Sprint', 'end': today + two_weeks}
>>> response = requests.post(api['sprints'], data=data, auth('demo', 'test'))
File "<stdin>", line 1
SyntaxError: non-keyword arg after keyword arg
>>> data
{'name': 'Current Sprint', 'end': datetime.date(2015, 3, 26)}
>>>

from looking at the 'data' it looks like the value "datetime.date(2015, 3, 26)" maybe at fault. According to the previous examples the 'end' is looking for YYYY-MM-DD formatted date.

So I tried:

>>> data = {'name': 'Current Sprint', 'end': datetime.date.isoformat(today + two_weeks)}
>>> data
{'name': 'Current Sprint', 'end': '2015-03-26'}
>>>

Data looks better. ... 'end': '2015-03-26' ... now.

So I tried it again and got the same error:

>>> response = requests.post(api['sprints'], data=data, auth('demo', 'test'))
File "<stdin>", line 1
SyntaxError: non-keyword arg after keyword arg
>>>

I'm lost now. Can you see anything that I'm doing wrong? Thanks.

Page 125 Chapter 5

I cannot get the authentication to let me through after submitting the form. I keep getting a 403 error, saying the CSRF token is missing. Searching shows I should add

{% csrf_token %}

to my form post method. I am unable to find the source of this error after comparing my code to yours. I'm totally unable to figure out why I can't get past this.

I've gotten to the styled login template successfully rendering.

Pillow - "decoder zip not available"

Hey all,

If anyone runs into this problem when trying to load the placeholder view after creating your generate method:

  • Uninstall Pillow version 2.9.0 and just run pip install Pillow to get the most recent version. This ended up working for me!

-Max

Why no TaskViews?

Thank you for the book, I'm learning tons.

Why no TaskItemView and TaskDetailView in the examples? The second half of chapter 6 is missing.

I've built it up following the book, can see here https://github.com/djangopractice/scrum_ui. Notice I've split into two repos: scrum and scrum_ui. Thought process is: the API controls the data model and should be app agnostic - we could build many UIs, even using different languages.

Two problems:

  1. I cannot Add Task. In the book you state "We now have a fully functioning Backbone application with the ability to add sprints and tasks and edit them while working with our REST API." Is this a known problem or did I miss something?

  2. I cannot change the status of a task with scrum_ui. Same question: known limitation or did I miss something?

Thanks for your consideration. If these are known limitations, no biggie, the purpose is to introduce how to use Backbone views and models with Underscore to make a client side single page application. Making Add Task and change task status work is a good homework assignment to sink in the lesson.

Chapter 4 links - serializer method field

Consider this an RFI,

I'm having trouble with adding links to the DRF serializers, seemingly, the "detail-view" doesn't exist anywhere, and I get a NoReverseMatch error

Reverse for 'sprint-detail' not found. 'sprint-detail' is not a valid view function or pattern name.

I am using latest django and python 3.6.

if obj.sprint_id:

if obj.sprint_id:
links['sprint'] = reverse('sprint-detail',
kwargs={'pk': obj.sprint_id}, request=request)
if obj.assigned:

template doesn't exist for Django 2.0

To avoid the error above, change:
TEMPLATE_DIRS=(
os.path.join(BASE_DIR, 'templates'),
),
to TEMPLATES= [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
}]
for it to work properly

Chapter 1/2 Create a New Project

When I create a new project with the command:

django-admin.py startproject foo --template=project_name

or:

django-admin.py startproject placeholder --template=project_name

I get:

CommandError: couldn't handle project template project_name.

The command is creating a folder named "foo" and "placeholder," but it's not creating the .py file within them. I know you provided your code for checkout, but I'd rather figure out why this isn't working. Full code snippet is below:

import os
import sys

from django.conf import settings

DEBUG = os.environ.get('DEBUG', 'on') == 'on'

SECRET_KEY = os.environ.get('SECRET_KEY', '{{ secret_key }}')

ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'localhost').split(',')


settings.configure(
    DEBUG=DEBUG,
    SECRET_KEY=SECRET_KEY,
    ALLOWED_HOSTS=ALLOWED_HOSTS,
    ROOT_URLCONF=__name__,
    MIDDLEWARE_CLASSES=(
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        ),
    )


from django.conf.urls import url
from django.core.wsgi import get_wsgi_application
from django.http import HttpResponse


def index(request):
    return HttpResponse('Hello World')

urlpatterns = (
    url(r'^$', index),
    )

application = get_wsgi_application()

if __name__ == "__main__":
    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

Issue with chapter 3 and BASEDIR

Hello,
As I was working with the code in chapter three I got as far as the runserver command prior to figure 3-2 trying to test what I had created so far. Anyhow, it was not rendering any of my pages.

I kept getting "Page not found (404)", I also tried using the example code from github for the chapter. It didn't work either.

I narrowed down the problem to the BASE_DIR setting from my testing.

My Test script


    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    import os

    BASE_DIR = os.path.dirname(os.path.dirname(__file__))
    print("executing: os.path.dirname(os.path.dirname(__file__))\nreturns: "
        + BASE_DIR)

    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    print('\n')

    print('executing: os.path.dirname(os.path.abspath(__file__))\nreturns: ' + BASE_DIR)
    print('\n')



The results I got were as follows:  (and yes I did use python 34 ;-) this time)


IN WINDOWS CMD
C:\Users\WindozeUser\Desktop\django\codefix>c:\Python34\python.exe test.py
executing: os.path.dirname(os.path.dirname(__file__))
returns:

executing: os.path.dirname(os.path.abspath(__file__))
returns:  C:\Users\WindozeUser\Desktop\django\codefix

IN Ubuntu BASH


    bashuser@localhost:~$ python test.py
    executing: os.path.dirname(os.path.dirname(__file__))
    returns:

    executing: os.path.dirname(os.path.abspath(__file__))
    returns: /home/bashuser

If I change the 'BASE_DIR = os.path.dirname(os.path.dirname(__file__))' to 'BASE_DIR = os.path.dirname(os.path.abspath(__file__))' (as in my test.py file above) within the prototypes.py file the website works as described in the book.

Being a newbie to all of this I'm a bit confused.  I may be miss informed, but I thought __file__ should be the name of module being executed?  But it doesn't seem to be in this context.

I don't know enough about python to have an opinion.  I just know it didn't work out of the box... which irks me a bit, especially when I've paid for something to learn from.

Which I guess I'm doing ;-)

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.