Code Monkey home page Code Monkey logo

django-2-by-example's Introduction

Django 2 by Example

This is the code repository for Django 2 by Example, published by Packt. It contains all the supporting project files necessary to work through the book from start to finish.

⚠️ New edition available

Check out the source code for the latest edition of this book: Django 4 by Example

About the Book

If you want to learn about the entire process of developing professional web applications with Django, then this book is for you. This book will walk you through the creation of four professional Django projects, teaching you how to solve common problems and implement best practices.

You will learn how to build a blog application, a social image-bookmarking website, an online shop, and an e-learning platform. The book will teach you how to enhance your applications with AJAX, create RESTful APIs, and set up a production environment for your Django projects. The book walks you through the creation of real-world applications, while solving common problems and implementing best practices. By the end of this book, you will have a deep understanding of Django and how to build advanced web applications

Instructions and Navigations

All of the code is organized into folders. Each folder starts with a number followed by the application name. For example, Chapter01.

The code will look like the following:


if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

Related Products

Download a free PDF

If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to download a free PDF copy of this book.

https://packt.link/free-ebook/9781788472487

django-2-by-example's People

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  avatar  avatar  avatar  avatar

django-2-by-example's Issues

Chapter 13 ImportError: No module named 'tutorial'

After download only Chapter 13 and on the start appears " No module named "tutorial". Where is the "tutorial" from? And how to solve this?

Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 60, in execute
super().execute(*args, **options)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 353, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 67, in handle
if not settings.DEBUG and not settings.ALLOWED_HOSTS:
File "/usr/local/lib/python3.5/dist-packages/django/conf/init.py", line 57, in getattr
self._setup(name)
File "/usr/local/lib/python3.5/dist-packages/django/conf/init.py", line 44, in _setup
self._wrapped = Settings(settings_module)
File "/usr/local/lib/python3.5/dist-packages/django/conf/init.py", line 107, in init
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/usr/lib/python3.5/importlib/init.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 986, in _gcd_import
File "", line 969, in _find_and_load
File "", line 944, in _find_and_load_unlocked
File "", line 222, in _call_with_frames_removed
File "", line 986, in _gcd_import
File "", line 969, in _find_and_load
File "", line 944, in _find_and_load_unlocked
File "", line 222, in _call_with_frames_removed
File "", line 986, in _gcd_import
File "", line 969, in _find_and_load
File "", line 956, in _find_and_load_unlocked
ImportError: No module named 'tutorial'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "manage.py", line 15, in
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/init.py", line 381, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.5/dist-packages/django/core/management/init.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 329, in run_from_argv
connections.close_all()
File "/usr/local/lib/python3.5/dist-packages/django/db/utils.py", line 220, in close_all
for alias in self:
File "/usr/local/lib/python3.5/dist-packages/django/db/utils.py", line 214, in iter
return iter(self.databases)
File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 37, in get
res = instance.dict[self.name] = self.func(instance)
File "/usr/local/lib/python3.5/dist-packages/django/db/utils.py", line 147, in databases
self._databases = settings.DATABASES
File "/usr/local/lib/python3.5/dist-packages/django/conf/init.py", line 57, in getattr
self._setup(name)
File "/usr/local/lib/python3.5/dist-packages/django/conf/init.py", line 44, in _setup
self._wrapped = Settings(settings_module)
File "/usr/local/lib/python3.5/dist-packages/django/conf/init.py", line 107, in init
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/usr/lib/python3.5/importlib/init.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 986, in _gcd_import
File "", line 969, in _find_and_load
File "", line 944, in _find_and_load_unlocked
File "", line 222, in _call_with_frames_removed
File "", line 986, in _gcd_import
File "", line 969, in _find_and_load
File "", line 944, in _find_and_load_unlocked
File "", line 222, in _call_with_frames_removed
File "", line 986, in _gcd_import
File "", line 969, in _find_and_load
File "", line 956, in _find_and_load_unlocked
ImportError: No module named 'tutorial'

Chapter 01 with Django 3

When I'm using class PostListView in the end of chapter 01, I have a problem: at the bottom of http://localhost:8000/blog/ numbers of pages with links dissappear. I see only "Page of" there.
Is it a problem of Django 3?
Can I add something to class PostListView to solve this problem?

Error when User have no photo in their profile

in this template, Django-2-by-Example/Chapter06/bookmarks/images/templates/images/image/detail.html
on line 38, gives an error if the user have no uploaded photo.[photo field is optional]

Altering the line with this can solve the problem,
<img src="{% if user.profile.photo %} {{ user.profile.photo.url }} {% endif %}">

Chapter 13. Resource Was Not Found

Hi, i encountered some problem. When I opened the site, what appeared was something like Not Found The requested resource was not found on this server.

I'm still trying figure it out what causes that, as for concern, i also set debug to True to see what the error is it and there is such an message like No Course matches the given query. I'm not sure if i missed something or not, cause i've ensure the urls configuration in path already matched and i'm also migrated the database.

Can anyone help? thank you

Chapter04 ModuleNotFoundError: No module named 'social_django'

Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/Django-2-by-Example-master/Chapter04/bookmarks/manage.py", line 15, in
execute_from_command_line(sys.argv)
File "C:\Python36\lib\site-packages\django\core\management_init_.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Python36\lib\site-packages\django\core\management_init_.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python36\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute
super().execute(*args, **options)
File "C:\Python36\lib\site-packages\django\core\management\base.py", line 364, in execute
output = self.handle(*args, **options)
File "C:\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle
self.run(**options)
File "C:\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 102, in run
autoreload.run_with_reloader(self.inner_run, **options)
File "C:\Python36\lib\site-packages\django\utils\autoreload.py", line 585, in run_with_reloader
start_django(reloader, main_func, *args, **kwargs)
File "C:\Python36\lib\site-packages\django\utils\autoreload.py", line 570, in start_django
reloader.run(django_main_thread)
File "C:\Python36\lib\site-packages\django\utils\autoreload.py", line 288, in run
self.run_loop()
File "C:\Python36\lib\site-packages\django\utils\autoreload.py", line 294, in run_loop
next(ticker)
File "C:\Python36\lib\site-packages\django\utils\autoreload.py", line 334, in tick
for filepath, mtime in self.snapshot_files():
File "C:\Python36\lib\site-packages\django\utils\autoreload.py", line 350, in snapshot_files
for file in self.watched_files():
File "C:\Python36\lib\site-packages\django\utils\autoreload.py", line 249, in watched_files
yield from iter_all_python_module_files()
File "C:\Python36\lib\site-packages\django\utils\autoreload.py", line 103, in iter_all_python_module_files
return iter_modules_and_files(modules, frozenset(_error_files))
File "C:\Python36\lib\site-packages\django\utils\autoreload.py", line 136, in iter_modules_and_files
if not path.exists():
File "C:\Python36\lib\pathlib.py", line 1336, in exists
self.stat()
File "C:\Python36\lib\pathlib.py", line 1158, in stat
return self._accessor.stat(self)
File "C:\Python36\lib\pathlib.py", line 387, in wrapped
return strfunc(str(pathobj), *args)
OSError: [WinError 123] 文件名、目录名或卷标语法不正确。: ''

module markdown not found error in Chapter 3

I just fixed one challenge while using markdown. If you are using the latest version of Python 3. You may run into the module not found error. You can fix the same by installing:
pip install django-markdown-deux
restart server and you should be able to fix the error

Charpter 02: AttributeError

In file Chapter02/mysite/blog/views.py, when I'm clicking the Add comment button:

AttributeError: 'CommentForm' object has no attribute 'save'

In this line of code:

new_comment = comment_form.save(commit=False)
                           ^^^^

Versions:

Django == 2.0.13
Python == 3.7.12

Chapter 09

The product recommendation system gives an error. "zincrby() got multiple values for argument 'amount'"
def products_bought(self, products): product_ids = [p.id for p in products] for product_id in product_ids: for with_id in product_ids: # get the other products bought with each product if product_id != with_id: # increment score for product purchased together r.zincrby(self.get_product_key(product_id), with_id, amount=1)

Python 3.7.9, Django 3, Redis server v=3.0.6

Tell me what could be the problem?

Chapter 12. detail_route deprecated from DRF 3.8

Chapter 12 uses the @detail_route decorator. It is outdated in the latest versions of DRF.
It is used here : /courses/api/views.py in CourseViewSet class.
Example: from rest_framework.decorators import detail_route

confused

please is the social website part of the blog? or i should create a new project?

Chp 4: Facebook social authentication no longer works

The instructions for social authentication with Facebook no longer work because Facebook now requires all apps to use HTTPS:

On October 6, 2018, all apps will be required to use HTTPS.

Thus it results in the error message from Facebook:

Facebook has detected Bookmarks isn't using a secure connection to transfer information.
Until Bookmarks updates its security settings, you won't be able to use Facebook to log into it.

I tried following the advice from this SO answer by changing the OAuth Redirect URI to https://localhost:8000/social-auth/complete/facebook/, but I got the same error.

Chapter 02: Adding comments

Has anyone else had any issues when adding the comments feature? I have all the code in, and via a get request my form renders properly to add a comment. However, when I fill in the comment fields, and hit the submit button, my template won't render. The slug isn't being passed to the url. The year, month, and date are. Did anyone else experience this? I'm completely stuck. There aren't any typos in my code because I copy and pasted it out of github into my file.

chapter 1: model manager does not work.

when adding an article through the admin panel, you need to change the status to "published" then your code works!

or by default assign the desired status:

status = models.CharField(max_length=10,
                              choices=STATUS_CHOICES,
                              default='published')

Your manager is looking for only published articles, but by default there is a different status(default='draft'), through the admin panel you can set the desired status of the article, but when users write articles, the status will be generated automatically and then not a single article will fall under your search!

good tutorial! thanks

Chapter 5 AttributeError: 'super' object has no attribute 'save'

the part of Overriding the save() method of a ModelForm in chapter 5 I have implemented code to overriding the save() method but give me an error
AttributeError: 'super' object has no attribute 'save' in line
image = super(ImageCreateForm, self).save(commit=False) in forms.py
and other thing in views.py why is added this line cd = form.cleaned_data
and actually we don't use it in our code

Chapter 02 an error in views.py "name 'send_mail' is not defined"

I have the error: "name 'send_mail' is not defined" in this part of code:
def post_share(request, post_id):
post = get_object_or_404(Post, id=post_id, status='published')
sent = False
if request.method == 'POST' :
form = EmailPostForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
post_url = request.build_absolute_uri(post.get_absolute_url())
subject = '{} ({}) recommends you reading"{}"'.format(cd['name'],cd['email'], post.title)
message = 'Read "{}" at {}\n\n{}'s comments: {}'.format(post.title, post_url, cd['name'],cd['comments'])
send_mail(subject, message, '[email protected]', [cd['to']])
sent = True
else:
form = EmailPostForm()
return render(request, 'blog/post/share.html', {'post': post, 'form': form, 'sent' : sent})

How to fix this error?

Chapter 1 - Pagination Not working - Django 2.1

the "base.html" isn't loading the css even though i have the directory setup exactly the same and copy and pasted the css and html files to make sure i didn't have any typos.

Or , it might be in the list.html file that is no showing my published articles.

Chapter 09 - parler TypeError when running "migrate shop"

After updating models for the shop app, makemigrations runs successfully, but migrate fails with this error:

TypeError: Translatable model <class 'fake.Product'> does not appear to inherit from TranslatableModel

Found this post with a fix that works. It does require a change to the migration file 0002_translations.py

I copied the models from the git repo. Is it my environment or does this happens to everyone?

I'm running my dev environment on Windows 10. Here's my pip freeze:
amqp==2.5.2
asgiref==3.2.7
astroid==2.3.3
billiard==3.6.3.0
braintree==4.0.0
cairocffi==1.1.0
CairoSVG==2.4.2
celery==4.4.2
certifi==2020.4.5.1
cffi==1.14.0
chardet==3.0.4
colorama==0.4.3
cssselect2==0.3.0
defusedxml==0.6.0
Django==3.0.5
django-parler==2.0.1
django-rosetta==0.9.4
flower==0.9.4
html5lib==1.0.1
humanize==0.5.1
idna==2.9
isort==4.3.21
kombu==4.6.8
lazy-object-proxy==1.4.3
mccabe==0.6.1
microsofttranslator==0.8
Pillow==7.1.1
polib==1.1.0
pycparser==2.20
pylint==2.4.4
Pyphen==0.9.5
pytz==2019.3
requests==2.23.0
six==1.14.0
sqlparse==0.3.1
tinycss2==1.0.2
tornado==6.0.4
urllib3==1.25.9
vine==1.3.0
WeasyPrint==51
webencodings==0.5.1
wrapt==1.11.2

I've been trying to install the latest versions to confirm these libraries are still usable.

Any pointers would be appreciated.

Thanks.

-J.

Reverse for 'register' not found. 'register' is not a valid view function or pattern name?

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/account/login/

Django Version: 2.0.6
Python Version: 3.6.4
Installed Applications:
['account',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed 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']


Template error:
In template /home/fc/Documents/1111/bookmarks/account/templates/base.html, error at line 13
   Reverse for 'register' not found. 'register' is not a valid view function or pattern name.
   3 : <html>
   4 : <head>
   5 :   <title>{% block title %}{% endblock %}</title>
   6 :   <link href="{% static "css/base.css" %}" rel="stylesheet">
   7 : </head>
   8 : <body>
   9 :   <div id="header">
   10 :     <span class="logo">Bookmarks</span>
   11 :     {% if request.user.is_authenticated %}
   12 :       <ul class="menu">
   13 :         <l i {% if section == " dashboard" %}class="selected"{% endif %}>
   14 :           <a href="{% url "dashboard" %}">My dashboard</a>
   15 :         </li>
   16 :         <li {% if section == "images" %}class="selected"{% endif %}>
   17 :           <a href="#">Images</a>
   18 :         </li>
   19 :         <li {% if section == "people" %}class="selected"{% endif %}>
   20 :           <a href="#">People</a>
   21 :         </li>
   22 :       </ul>
   23 :     {% endif %}


Traceback:

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  158.                 response = self.process_exception_by_middleware(e, request)

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  156.                 response = response.render()

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/template/response.py" in render
  106.             self.content = self.rendered_content

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/template/response.py" in rendered_content
  83.         content = template.render(context, self._request)

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/template/backends/django.py" in render
  61.             return self.template.render(context)

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/template/base.py" in render
  175.                     return self._render(context)

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/template/base.py" in _render
  167.         return self.nodelist.render(context)

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/template/base.py" in render
  943.                 bit = node.render_annotated(context)

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  910.             return self.render(context)

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/template/loader_tags.py" in render
  155.             return compiled_parent._render(context)

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/template/base.py" in _render
  167.         return self.nodelist.render(context)

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/template/base.py" in render
  943.                 bit = node.render_annotated(context)

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  910.             return self.render(context)

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/template/loader_tags.py" in render
  67.                 result = block.nodelist.render(context)

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/template/base.py" in render
  943.                 bit = node.render_annotated(context)

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  910.             return self.render(context)

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/template/defaulttags.py" in render
  314.                 return nodelist.render(context)

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/template/base.py" in render
  943.                 bit = node.render_annotated(context)

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  910.             return self.render(context)

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/template/defaulttags.py" in render
  447.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/urls/base.py" in reverse
  90.     return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))

File "/home/fc/.local/share/virtualenvs/1111-oxI__AFh/lib/python3.6/site-packages/django/urls/resolvers.py" in _reverse_with_prefix
  636.         raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /account/login/
Exception Value: Reverse for 'register' not found. 'register' is not a valid view function or pattern name.

views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth import authenticate, login
from .form import LoginForm
from django.contrib.auth.decorators import login_required
# 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(request,
                                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})

@login_required
def dashboard(request):
    return render(request, 'account/dashboard.html', {'section': 'dashboard'})

urls.py

from django.urls import path
from django.contrib.auth import views as auth_views
from . import views

urlpatterns =[
    # path('login/', views.user_login, name='login')
    path('login/', auth_views.LoginView.as_view(), name='login'),
    path('logout/', auth_views.LogoutView.as_view(), name='logout'),
    path('', views.dashboard, name='dashboard'),
]

Chapter 1 - Stylesheet

Hi,

I might be doing something wrong as I am quite new to programming but shouldn't we change the line:
STATIC_URL = '/static/' to:
STATIC_URL = '/blog/static/' in settings.py as we keep the static directory inside the blog app?
With the first option, editing the stylesheet does not make any changes to the blog, and after changing the line to the '/blog/static/' whenever i change anything in the blog.css file, all the changes are visible on the website.

I would be grateful for an answer.
Thanks

Chapter 2 comments with form dropping post name slug

This is in Chapter 2, the section where you add comments. There's a bug in the <form action="." tag. It worked when it was changed to an empty string <form action=""

If I used the code in the example (<form action="."), the post back url would drop the post title slug (but still keep the rest of the url.)
For example, instead of posting this url:
http://127.0.0.1:8000/blog/2018/8/22/test-post-admin
it would post this:
http://127.0.0.1:8000/blog/2018/8/22/

Again, the fix that worked for me was changing:
<form action="." method="post"> {{ comment_form.as_p }} {% csrf_token %} <p><input type="submit" value="Add comment"></p> </form>
to
<form action="" method="post"> {{ comment_form.as_p }} {% csrf_token %} <p><input type="submit" value="Add comment"></p> </form>

Chapter 10: django.db.utils.IntegrityError: NOT NULL constraint failed: courses_module.order

When working through Chapter 10: Adding ordering to module and content objects, I get this error when interacting with the shell:

(educa) brian@brian-pc ~/P/e/d/educa> python manage.py shell
Python 3.8.6 (default, Sep 25 2020, 09:36:53) 
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> from courses.models import Subject, Course, Module
>>> user = User.objects.last()
>>> subject = Subject.objects.last()
>>> c1 = Course.objects.create(subject=subject, owner=user, title='Course 1', slug='course1')
>>> m1 = Module.objects.create(course=c1, title='Module 1')
>>> m1.order
0
>>> m2 = Module.objects.create(course=c1, title='Module 2')
Traceback (most recent call last):
  File "/home/brian/Projects/experiments/django2byexample/env/educa/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/brian/Projects/experiments/django2byexample/env/educa/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: NOT NULL constraint failed: courses_module.order

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/brian/Projects/experiments/django2byexample/env/educa/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/brian/Projects/experiments/django2byexample/env/educa/lib/python3.8/site-packages/django/db/models/query.py", line 447, in create
    obj.save(force_insert=True, using=self.db)
  File "/home/brian/Projects/experiments/django2byexample/env/educa/lib/python3.8/site-packages/django/db/models/base.py", line 753, in save
    self.save_base(using=using, force_insert=force_insert,
  File "/home/brian/Projects/experiments/django2byexample/env/educa/lib/python3.8/site-packages/django/db/models/base.py", line 790, in save_base
    updated = self._save_table(
  File "/home/brian/Projects/experiments/django2byexample/env/educa/lib/python3.8/site-packages/django/db/models/base.py", line 895, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "/home/brian/Projects/experiments/django2byexample/env/educa/lib/python3.8/site-packages/django/db/models/base.py", line 933, in _do_insert
    return manager._insert(
  File "/home/brian/Projects/experiments/django2byexample/env/educa/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/brian/Projects/experiments/django2byexample/env/educa/lib/python3.8/site-packages/django/db/models/query.py", line 1254, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "/home/brian/Projects/experiments/django2byexample/env/educa/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1397, in execute_sql
    cursor.execute(sql, params)
  File "/home/brian/Projects/experiments/django2byexample/env/educa/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute
    return super().execute(sql, params)
  File "/home/brian/Projects/experiments/django2byexample/env/educa/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/home/brian/Projects/experiments/django2byexample/env/educa/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/home/brian/Projects/experiments/django2byexample/env/educa/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/brian/Projects/experiments/django2byexample/env/educa/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/brian/Projects/experiments/django2byexample/env/educa/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/brian/Projects/experiments/django2byexample/env/educa/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: courses_module.order

My model.py is exactly the same from the chapter:

from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.db.models.fields import URLField
from .fields import OrderField

class Subject(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, unique=True)

    class Meta:
        ordering = ['title']

    def __str__(self):
        return self.title

class Course(models.Model):
    owner = models.ForeignKey(User,
                              related_name='courses_created',
                              on_delete=models.CASCADE)
    subject = models.ForeignKey(Subject,
                                related_name='courses',
                                on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, unique=True)
    overview = models.TextField()
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created']

    def __str__(self):
        return self.title


class Module(models.Model):
    course = models.ForeignKey(Course,
                               related_name='modules',
                               on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    description = models.TextField(blank=True)
    order = OrderField(blank=True, for_fields=['course'])

    class Meta:
        ordering = ['order']

    def __str__(self):
        return '{}. {}'.format(self.order, self.title)

class Content(models.Model):
    module = models.ForeignKey(Module,
                               related_name='contents',
                               on_delete=models.CASCADE)
    content_type = models.ForeignKey(ContentType,
                                     on_delete=models.CASCADE,
                                     limit_choices_to={'model__in':(
                                                       'text',
                                                       'video',
                                                       'image',
                                                       'file')})
    object_id = models.PositiveIntegerField()
    item = GenericForeignKey('content_type', 'object_id')
    order = OrderField(blank=True, for_fields=['module'])

    class Meta:
            ordering = ['order']


class ItemBase(models.Model):
    owner = models.ForeignKey(User,
                              related_name='%(class)s_related',
                              on_delete=models.CASCADE)
    title = models.CharField(max_length=250)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True
    
    def __str__(self):
        return self.title

class Text(ItemBase):
    content = models.TextField()

class File(ItemBase):
    file = models.FileField(upload_to='files')

class Image(ItemBase):
    file = models.FileField(upload_to='images')

class Video(ItemBase):
    url = models.URLField()

I followed the instructions in the book when migrating the models:

You are trying to add a non-nullable field 'order' to content without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:

  1. Provide a one-off default now (will be set on all existing rows with a null value for this column)
  2. Quit, and let me add a default in models.py
    Select an option:

I select "1" and then enter "0" at the prompt.

I have also tried setting default=0 on the order fields for the Module and Content columns and running the migrations again, but that doesn't solve the problem.

app fix covered in ch3

Here's the error I get:

ProgrammingError at /admin/blog/post/
relation "blog_post" does not exist
LINE 1: SELECT COUNT() AS "__count" FROM "blog_post"
^
Request Method: GET
Request URL: https://xxx.herokuapp.com/admin/blog/post/
Django Version: 2.2.5
Exception Type: ProgrammingError
Exception Value:
relation "blog_post" does not exist
LINE 1: SELECT COUNT(
) AS "__count" FROM "blog_post"
^
Exception Location: /app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py in _execute, line 84
Python Executable: /app/.heroku/python/bin/python
Python Version: 3.7.3
Python Path:
['/app/.heroku/python/bin',
'/app',
'/app/.heroku/python/lib/python37.zip',
'/app/.heroku/python/lib/python3.7',
'/app/.heroku/python/lib/python3.7/lib-dynload',
'/app/.heroku/python/lib/python3.7/site-packages']
Server time: Thu, 12 Sep 2019 18:34:34 +0000

Any ideas on how to fix this?

Label Chapters

If you read an electronic version of this book in Kindle Reader or Apple Books, the chapters just have names, no chapter numbers. But this repository just shows chapter numbers. The repo would be easier to use if the chapter title (e.g. "Building a Blog Application") was included along side the chapter number or if there was at least a README inside each folder mapping that chapter to a chapter in the electronic book version.

Chp 4: Updates to Twitter social authentication instructions

I was able to get the social authentication via Twitter working. However, Twitter has made some changes since the publication of this book:

  • apps.twitter.com was replaced by developer.twitter.com (it of course redirects to this new URL)
  • The app name has to be unique. When I tried using "Bookmarks", I received the error "appName: Bookmarks is already taken for Name"
  • There is now a checkbox Enable Sign in with Twitter that needs to be checked
  • It is now required to describe how the app will be used (only visible to Twitter employees)

Chapter 9 | Extending the admin site with custom views | admin.css

In Chapter 9 you reference a static/ directory for the orders application...

image

...but you do not have that pushed to GitHub.

image

Could you please add it or advise how I can access these static files. Specifically admin.css as that is the one that I'm specifically needing now. However, I'm not sure if any other static assets are mentioned later in this course.

Thank you!

Chapter 04 Email sending

Hello, I am not able to send email and print out on the console. I am not sure where I am making mistake. Can you help me ?

Bookrmarklet_launcher.js issue

In dashboard.html, the current way of linking the bookmarklet doesn't work. I am able to drag the button into the bookmarks bar, but the script itself doesn't work. The output to the console shows that for some reason including the script within the href slices the it. The script stops at the first line and appears incomplete.
The following temporary fix of pasting the script directly + turning it into a button seems to work:

<p>Drag the following button to your bookmarks toolbar to bookmark images from other websites → <a href="javascript: (function() { if (window.myBookmarklet !== undefined) { myBookmarklet(); } else { document.body.appendChild(document.createElement('script')).src = 'https://7605a314.ngrok.io/static/js/bookmarklet.js?r=' + Math.floor(Math.random() * 99999999999999999999); } })();"><button>Bookmark it</button><p> </a>

Chapter 01 Instance of 'DateTimeField' has no 'day' member

I followed the example in the chapter 01 and I get the error "Instance of 'DateTimeField' has no 'day' member", so, I thought there I have a mistake, and then downloaded the full example, and get the same error.

I use django version 2.2.2
and python 3.7.0 32-
Captura
bit

Chapter 1 . List view error

Hi , I also have the issue with list view. I followed the instructions. It looks for detail view and I have not created the detail view. When i set one post to publish and then look at the site, it throws error. The if all are in draft the Html page does show up.

The error:

Request Method: GET
http://127.0.0.1:8000/blog/
3.0.6
NoReverseMatch
Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name.
/Users/jayakumare/pusth-site/pusth_env/lib/python3.8/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677

Originally posted by @ejk3052 in #19 (comment)

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.