GithubHelp home page GithubHelp logo

mdn / django-locallibrary-tutorial Goto Github PK

View Code? Open in Web Editor NEW
1.5K 78.0 925.0 318 KB

Local Library website written in Django; example for the MDN server-side development Django module: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django.

License: Creative Commons Zero v1.0 Universal

Python 77.78% CSS 0.18% HTML 21.92% Procfile 0.12%

django-locallibrary-tutorial's Introduction

Django Local Library

Tutorial "Local Library" website written in Django.

For detailed information about this project see the associated MDN tutorial home page.

Overview

This web application creates an online catalog for a small local library, where users can browse available books and manage their accounts.

The main features that have currently been implemented are:

  • There are models for books, book copies, genre, language and authors.
  • Users can view list and detail information for books and authors.
  • Admin users can create and manage models. The admin has been optimised (the basic registration is present in admin.py, but commented out).
  • Librarians can renew reserved books

Local Library Model

Quick Start

To get this project up and running locally on your computer:

  1. Set up the Python development environment. We recommend using a Python virtual environment.

    Note: This has been tested against Django 3.10 (and may not work or be "optimal" for other versions).

  2. Assuming you have Python setup, run the following commands (if you're on Windows you may use py or py -3 instead of python to start Python):
    pip3 install -r requirements.txt
    python3 manage.py makemigrations
    python3 manage.py migrate
    python3 manage.py collectstatic
    python3 manage.py test # Run the standard tests. These should all pass.
    python3 manage.py createsuperuser # Create a superuser
    python3 manage.py runserver
    
  3. Open a browser to http://127.0.0.1:8000/admin/ to open the admin site
  4. Create a few test objects of each type.
  5. Open tab to http://127.0.0.1:8000 to see the main site, with your new objects.

django-locallibrary-tutorial's People

Contributors

alextugarev avatar alexvorndran avatar andrewtavis avatar artursniegowski avatar bsmth avatar chrisdavidmills avatar dependabot[bot] avatar desagaz avatar dipikabh avatar f1ashhimself avatar gacheiro avatar hamishwillee avatar j9peters avatar leverimmy avatar lmeerwood avatar mozilla-github-standards avatar ozgurturkiye avatar vladyslavhnatchenko 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  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-locallibrary-tutorial's Issues

Adding more challenges, explanations to challenge solutions

Hi

Thanks for creating this excellent tutorial for Django beginners.

It is the best I've found so far, even better than the one provided by Django official site.

While following the tutorial I really enjoyed having some challenges at the end of each step, that's something that you guys can expand on maybe? (adding more challenges)

Also another thing that will be very beneficial for new programmers is understanding some architecture decisions when developing (Models Challenge)

So I think it will be good to have in the next chapter of working with models an explanation on why Language was implemented that way and not in any other possible way.

That can be applicable to any challenge that requires architecture decisions in other chapters.

(Sorry if this is not the appropriate place to comment about this, I didn't found any other place where to post this)

NoReverseMatch - Reverse for 'logout' not found.

I get this error (front end only, back end works fine):

NoReverseMatch at /catalog/
Reverse for 'logout' not found. 'logout' is not a valid view function or pattern name.
Request Method: GET
Request URL: http://127.0.0.1:8000/catalog/
Django Version: 3.1.2
Exception Type: NoReverseMatch
Exception Value: Reverse for 'logout' not found. 'logout' is not a valid view function or pattern name.

Completely new install.
Django 3.1.2
Python 3.9.7

views.py DetailView

Spent the longest time on this, I had to specifically import Detail View like so
from django.views.generic.detail import DetailView

from django.views import generic

doesn't seem to work, throwing this:

 class BookDetailView(DetailView):
NameError: name 'DetailView' is not defined

I'm using python 3.6 and django 2.02 (on ubuntu 16.04)

Discrepancy in test_views RE permission error tests

While working through part 10, I ran into some behavior that has confused me.

  1. It seems that the status code indicated in the tutorial is incorrect in one of our unit tests (RenewBookInstancesViewTest.test_redirect_if_logged_in_but_not_correct_permission()), based on the behavior I've seen + what is shown in the file in the repository (link to relevant line, 330). The test failed before I updated the status code to 302, and its behavior makes sense as such (when logged in with a user without the relevant permission, it redirects to a login page with a prompt at the top to provide credentials for a user that has permission).
  2. It seems that the error code again is wrong in AuthorCreateViewTest, as the test_redirect_if_logged_in_but_not_correct_permission() unit tests fails, returning:
self.assertEqual(response.status_code, 403)
AssertionError: 302 != 403

This is quite confusing as, when replicating the test in a browser results in a "403 Forbidden" and "GET /catalog/author/create/ HTTP/1.1" 403 22 is shown in the terminal.

As far as I can see, the primary difference is that renew_book_librarian() function uses the @permission_required decorator rather than the PermissionRequiredMixin used in the AuthorCreate

CODE_OF_CONDUCT.md file missing

As of January 1 2019, Mozilla requires that all GitHub projects include this CODE_OF_CONDUCT.md file in the project root. The file has two parts:

  1. Required Text - All text under the headings Community Participation Guidelines and How to Report, are required, and should not be altered.
  2. Optional Text - The Project Specific Etiquette heading provides a space to speak more specifically about ways people can work effectively and inclusively together. Some examples of those can be found on the Firefox Debugger project, and Common Voice. (The optional part is commented out in the raw template file, and will not be visible until you modify and uncomment that part.)

If you have any questions about this file, or Code of Conduct policies and procedures, please see Mozilla-GitHub-Standards or email [email protected].

(Message COC001)

Outdated dependencies (whitenoise & psycopg2)

Hi - deploying this to Heroku fails due to a breaking change in the latest version of Whitenoise (http://whitenoise.evans.io/en/stable/changelog.html#v4-0)

Removing any reference to whitenoise in wsgi.py seems to resolve it.

There's also a breaking change on deployment with psycopg2. Buried in the Heroku logs is the advice to now use pip install psycopg2-binary rather than pip install psycopg2 - this seems to resolve the issue

Edit: as far as I can tell replacing psycopg2 with psycopg2-binary also leads to a failed build,
Leaving them both in seems to prevent the database from being properly created on the server (runtime error relation catalog_book does not exist - this is the first time the app tries to get something from the db). It works ok locally (using sqlite.db).

test_renew_form_date_max test failure

Form validation (from catalog/forms.py) uses datetime in all cases to generate the date.

def clean_renewal_date(self):
        data = self.cleaned_data['renewal_date']
        
        #Check date is not in past. 
        if data < datetime.date.today():
            raise ValidationError(_('Invalid date - renewal in past'))
        #Check date is in range librarian allowed to change (+4 weeks)
        if data > datetime.date.today() + datetime.timedelta(weeks=4):
            raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead'))

        # Remember to always return the cleaned data.
        return data

The test function test_renew_form_date_max() uses timezone.now() and a datetime.timedelta() to create the date to bind to the form for validation. Is this breaking the test since timezone.now() uses UTC?

def test_renew_form_date_max(self):
        """
        Test form is valid if renewal_date is within 4 weeks
        """
        date = timezone.now() + datetime.timedelta(weeks=4)
        form_data = {'renewal_date': date}
        form = RenewBookForm(data=form_data)
        self.assertTrue(form.is_valid())

catalog.urls.py? Server not able to start while going through part 2 of tutorial

Hi,
I'm following along the tutorial and I'm stuck. When I enter the command python3 manage.py makemigrations, I get the following output:

Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/management/base.py", line 332, in execute self.check() File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/stephen/Documents/locallibrary/locallibrary/locallibrary/urls.py", line 27, in <module> path('catalog/', include('catalog.urls')), File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'catalog.urls'

When I enter the command python3 manage.py runserver, I get the following:

`
Performing system checks...

Unhandled exception in thread started by <function check_errors..wrapper at 0x7fbea1d9c730>
Traceback (most recent call last):
File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run
self.check(display_num_errors=True)
File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/urls/resolvers.py", line 397, in check
for pattern in self.url_patterns:
File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/utils/functional.py", line 36, in get
res = instance.dict[self.name] = self.func(instance)
File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/utils/functional.py", line 36, in get
res = instance.dict[self.name] = self.func(instance)
File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module
return import_module(self.urlconf_name)
File "/home/stephen/.virtualenvs/my_django_environment/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 958, in _find_and_load_unlocked
File "", line 673, in _load_unlocked
File "", line 665, in exec_module
File "", line 222, in _call_with_frames_removed
File "/home/stephen/Documents/locallibrary/locallibrary/locallibrary/urls.py", line 27, in
path('catalog/', include('catalog.urls')),
File "/home/stephen/.virtualenvs/my_django_environment/lib/python3.5/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/home/stephen/.virtualenvs/my_django_environment/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 956, in _find_and_load_unlocked
ImportError: No module named 'catalog.urls'

`

It seems that there needs to be a catalog.urls file that should've been included when the files for the catalog app was generated (with the python3 manage.py startapp catalog command), but it isn't, and even the tutorial acknowledges that it wasn't and says that we'd be getting back to that issue later. When I try to start the app, it's not starting because it looks like the app server relies on that file being there. What am I missing?

Copy skeleton into a new project

Before submitting the issue, confirm that you've checked everything in the following list, and mark them as completed here:

  • Issue is reproducible on this repository by following the quick-start instructions.
  • A clean/fresh database was used when the issue was encountered.
  • Information about the environment setup when the issue was encountered is included in the issue.
  • Output logs are included in the issue.

What was incorrect, unhelpful, or unexpected?

How do I copy the Django/skeleton_website into a new project? I am a beginner so please give me step-by-step instructions.

What did you expect to see?

Step-by-step instructions on how to copy the Django/skeleton_website into a new project

Output logs

No response

Do you have anything more you want to share?

No response

Improving Pagination step

I think the Pagination step could benefit from an update.

When expanding the base template users are told to add a pagination block under the content block. Simple enough, right? Well, new users are still becoming acquainted with content blocks , and up until now in the tutorial their primary interaction with content blocks has been within templates extending the base template. I'd go so far as to wager that most failed to notice the content block tags when the base_generic.html file was introduced. Perceptive users might notice it during updating the sidebar-nav task but that was a while ago relative to this pagination task. To drive home my concern the tutorial instructions add to confusion with the line

...copy in the following pagination block below our content block (highlighted below in bold).

However, no highlighting is found.

My suggested fix would be to restate the entire base_generic.html file. Yes, it is a bit repetitive but given the length and depth of MDN's Django tutorial compared to its peers a little extra length can't hurt. Below should be all the html for the base up to this point in the tutorial.

<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
  
  <!-- Add additional CSS in static file -->
  {% load static %}
  <link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-2">
      {% block sidebar %}
        <ul class="sidebar-nav">
          <li><a href="{% url 'index' %}">Home</a></li>
          <li><a href="{% url 'books' %}">All books</a></li>
          <li><a href="{% url 'authors'%}">All authors</a></li>
        </ul>
     {% endblock %}
      </div>
      <div class="col-sm-10 ">{% block content %}{% endblock %}

        <!-- pagination starts here-->
        {% block pagination %}
          {% if is_paginated %}
          <div class="pagination">
            <span class="page-links">
              {% if page_obj.has_previous %}
              <a href="{{ request.path }}?page={{ page_obj.previous_page_number }}">previous</a>
              {% endif %}
              <span class="page-current">
                Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
              </span>
              {% if page_obj.has_next %}
              <a href="{{ request.path }}?page={{ page_obj.next_page_number }}">next</a>
              {% endif %}
            </span>
          </div>
          {% endif %}
        {% endblock %}
        <!-- pagination starts here-->

      </div>
    </div>
  </div>
</body>
</html>

Aside from my formatting the only things I've done here is explicitly point out the pagination block within the base template using comments. This will accomplish 2 things:

  1. Remind users that all templates can be edited to produce broad and immediate changes.
  2. Present users with an immediate example.

Typo in tutorial page

small typo in https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Forms#The_template
there is an additional ">" symbol in line 6 <p> tag:

{% extends "base_generic.html" %}

{% block content %}
  <h1>Renew: {{ book_instance.book.title }}</h1>
  <p>Borrower: {{ book_instance.borrower }}</p>
  <p>{% if book_instance.is_overdue %} class="text-danger"{% endif %}>Due date: {{ book_instance.due_back }}</p>
    
  <form action="" method="post">
    {% csrf_token %}
    {{ form.as_table }}
    <input type="submit" value="Submit">
  </form>
{% endblock %}
typo line :  <p>{% if book_instance.is_overdue %} class="text-danger"{% endif %}> ...
correction:  <p{% if book_instance.is_overdue %} class="text-danger"{% endif %}> ...

(code in github is correct)

Language Options

I've got up to chapter 11 now but I really want to try and add some books to the database in admin. Is it possible for MDN to share the code for the language options as without this I cannot add any book because its required field. I have making choices but did not work.

any help much appreciated, by the way. Real good tutorial!

'RenewBookForm' object has no attribute 'cleaned_data'

When trying to 'renew' a book, I get the error:
'RenewBookForm' object has no attribute 'cleaned_data'

If I change the code from
book_instance.due_back = form.cleaned_data['renewal_date']
to
book_instance.due_back = form['renewal_date']
everything goes through but the date never updates.

Using non heroku install

So i commented out the heroku code in the app because I kept getting an error im just using pycharm on a local computer what do I have to change for this to work properly ? Thanks for the help

issues on ALLOWED_HOSTS

Hi, thanks for your code. it helps me a lot in learning django.
But when I want to deploy my code on AWS Elastic Beanstalk. It returns that I did not add the host to ALLOWED_HOSTS.
But in fact I have done that in localibrary/settings.py
I wonder if there is any other things to be done before I can get deploy it successfully?
thanks!

tutorial part 3

in models.py

class Book(models.Model):
title = models.CharField(max_length=200)

author = models.ForeignKey('Author', on_delete=models.SET_NULL, null = True)

summary = models.TextField(max_length = 1000, help_text= 'Enter a brief description of the book')

isbn = models.CharField(
    'ISBN', max_length=13, help_text='13 character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>')

genre = models.ManyToManyField(Genre, help_text = 'Select a genre for this book')

def __str__(self):
    return self.title

def get_absolute_url(self):
    return reverse('book-details', args=[str(self.id)])

there is no self.id in class Book and is giving an error
the get_absolute url seems to not work as the foriegn keys are not getting linked somehow

Problem with "/catalog/models.py"

My Django version: 2.2.5
In line 47: Instance of 'ManyToManyField' has no 'all' memberpylint(no-member).
In line 53: Instance of 'Book' has no 'id' memberpylint(no-member)
In line 101: Instance of 'ForeignKey' has no 'title' memberpylint(no-member)
In line 116: Instance of 'Author' has no 'id' memberpylint(no-member)

Template syntax error : Book instance "Renew"

I have been going through the tutorials on https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website.

Up until the Part 9 ("Working with forms") the app had been working as explained in the tutorials. But after created the functionality of "Renew" in the "All Borrowed Books" book lists, I have been getting the subject error.

Error text:

TemplateSyntaxError at /catalog/book/38c0acbc-04eb-4297-b531-66dd3177c29e/renew/

<Could not parse the remainder: '"base_generic.html' from '"base_generic.html'>

Request Method: 	GET
Request URL: 	http://127.0.0.1:8000/catalog/book/38c0acbc-04eb-4297-b531-66dd3177c29e/renew/
Django Version: 	2.0.6
Exception Type: 	TemplateSyntaxError
Exception Value: 	

Could not parse the remainder: '"base_generic.html' from '"base_generic.html'

Exception Location: 	/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/template/base.py in __init__, line 668
Python Executable: 	/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
Python Version: 	3.6.4
Python Path: 	

['/Users/**********/******/******/******/myLibrary/locallibrary',

'/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip',
'/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6',
'/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages']

I have gone thru' the related codes all over again (including tried "copy-pasting" codes from both the tutorial as well as the Github pages here) but every time I get the same error.

Grateful for a lead on this.
Thanks

get_status_display only returns the status not the LOAN_STATUS value

In the 5th tutorial when I was working on in the template section when we are looping over the book instances. I notice that the status and the display_status both had the same return value as "a" instead of availability. I checked the code and the display_status does only return self.status. I assumed that we would need a complete word from the LOAN_STATUS. So I modified the code as follows

def get_status_display(self):
        for key, value in enumerate(self.LOAN_STATUS):
            if value[0] == self.status:
                return self.LOAN_STATUS[key][1]
        return None

I hope this helps if anyone is interested in that.

Check if create home page correctly redirects to home page

From https://discourse.mozilla.org/t/django-local-library-project-creating-your-home-page-issues/24052

website programming section -> django -> Part 5: creating our home page.

At the end of this section you are supposed to load the home page using http://127.0.0.1:8000 and you are supposed to be redirected to http://127.0.0.1:8000/catalog which shows the books library home page. This is not what actually happens. When I load http://127.0.0.1:8000 I get a 404 error. However if I append /catalog then I get the books library home page. So my question is: is the tutorial incorrect or is this the expected behavior?

Authentication views

ERRORS:
?: (urls.E004) Your URL pattern [<URLResolver (admin:admin) 'admin/'>, <URLResolver <module 'catalog.urls' from 'C:\Users\Rahul\Documents\locallibrary\catalog\urls.py'> (None:None) 'catalog/'>, <URLPattern ''>, <URLPattern '^static/(?P.*)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances.

System check identified 1 issue (0 silenced).
allthe code matches still shows an error please help

Issue when logging out

Before submitting the issue, confirm that you've checked everything in the following list, and mark them as completed here:

  • Issue is reproducible on this repository by following the quick-start instructions.
  • A clean/fresh database was used when the issue was encountered.
  • Information about the environment setup when the issue was encountered is included in the issue.
  • Output logs are included in the issue.

What was incorrect, unhelpful, or unexpected?

so i followed the guide up till this part where it tests the logout (using the side bar but when i was logged out it displays the admin logout page and when i went back to home page it didn't even log out the user
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication#testing_the_new_authentication_pages

What did you expect to see?

user logged out page found in logged_out.html and also user properly logged out.

Output logs

No response

Do you have anything more you want to share?

No response

Are there plans to update to Django 3

I love your tutorial, I recommend it a lot in our Django group. I am curious, are there are plans to update the tutorial to Django 3?

I do not think async would be needed, and from what I understand async is still being worked on. This would make updating the tutorial a bit easier imo

Not following PEP8 Rules

Hi,

It's disheartening to see projects from mdn doesn't follow PEP8 rules in writing the code. Did you ever done a pylint and see the results ??

Handle case where Book belonging to Bookinstance is deleted.

Before submitting the issue, confirm that you've checked everything in the following list, and mark them as completed here:

  • Issue is reproducible on this repository by following the quick-start instructions.
  • A clean/fresh database was used when the issue was encountered.
  • Information about the environment setup when the issue was encountered is included in the issue.
  • Output logs are included in the issue.

What was incorrect, unhelpful, or unexpected?

The problem is described here mdn/content#27895 and the "base" of the solution is described in comment here: mdn/content#27895 (comment)

In short, this example stops at the same point as the tutorial challenge, which was creating forms for create, modify, delete, of books. It does not show any code for bookinstances.

However if you were to implement a bookinstance code, assign a book, and then you delete the book you get an error - because the book model requires you cannot delete a book unless all its instances are first deleted.

What did you expect to see?

We need to implement the bookinstance stuff as well (to ease testing) and override the book implementation to handle the error and provide a new view in this error case.

We should also create a Test for this case in the test cases, though that is not essential.

Output logs

Nope.

Do you have anything more you want to share?

Nope

"Please correct errors below"

After adding inline forms, I noticed that I was not able to use them or even save my Books anymore. I am getting an error at the top that says "Please correct errors below". After some meddling, I found it was due to my UUID id field that is my primary key was read_only. I made it a readonly field because I didn't think it made sense to be able to edit this. However, when it is made readonly, the form registers it as an error (with not error list) and does not let the Parent element or the Child instance be saved. I know this is not where this can be fixed, but I don't think we should use UUID as the pk when this is an issue.

date time picker not working

I tried all possible types but it wont work kindly give me a simple solution to add the date widget to it
thanks in advance

SystemCheckError

django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:

ERRORS:
<class 'catalog.admin.BookAdmin'>: (admin.E108) The value of 'list_display[2]' refers to 'display_genre', which is not a callable, an attribute of 'BookAdmin', or an attribute or method on 'catalog.Book'.
<class 'catalog.admin.BookInstanceAdmin'>: (admin.E108) The value of 'list_display[2]' refers to 'borrower', which is not a callable, an attribute of 'BookInstanceAdmin', or an attribute or method on 'catalog.BookInstance'.

remove uses of fields = '__all__'

there are many uses of fields = '__all__' this is an antipattern. If in the future the model is given a field that should not be updatable it will be exposed.

Better to explicitly list the fields than be implicit.

raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'renew-book-librarian' with arguments '(UUID('b3efb948-ab15-44dc-87af-50c6ede58c18'),)' not found. 1 pattern(s) tried: ['catalog/book/uuid:pk>/renew/$']

Good day and thank you for the material provided for learning. I followed tutorial 9 about forms everything worked fine till I clicked the link to be taken to the form area that was when I got a

` raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'renew-book-librarian' with arguments '(UUID('b3efb948-ab15-44dc-87af-50c6ede58c18'),)' not found. 1 pattern(s) tried: ['catalog/book/uuid:pk>/renew/$']
'

I have tried solving it for about a day now and I have been unable to solve it.

Missing import from documentation

Tutorial page https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication

Section: Project URLs
Snippet to add-in tutorial
#Add Django site authentication urls (for login, logout, password management) urlpatterns += [ url(r'^accounts/', include('django.contrib.auth.urls')), ]
The include method is missing from the snippet which causes a NameError NameError: name 'include' is not defined
Line required to add:
from django.conf.urls import include

Recommend change from "author" to "book" in book_confirm_delete.html

In the MDN Django Tutorial Part9, challenge, I tried the github code in book_confirm_delete.html, and found that it will lead to prompting the user attempting to delete a book record, whether they want to delete the author, where the prompt should be whether they want to delete the specific book that is numbered in the URL. The other files in github for this section are fine including sections of urls.py, views.py, and book_form.html

I recommend the following change in book_confirm_delete.html:

from:

{% extends "base_generic.html" %}
{% block content %}

Delete Author

Are you sure you want to delete the author: {{ author }}?

{% csrf_token %} {% endblock %}

to:

{% extends "base_generic.html" %}
{% block content %}

Delete Book

Are you sure you want to delete the book: {{ book }}?

{% csrf_token %} {% endblock %}

Visual Studio Code debugging

Before submitting the issue, confirm that you've checked everything in the following list, and mark them as completed here:

  • Issue is reproducible on this repository by following the quick-start instructions.
  • A clean/fresh database was used when the issue was encountered.
  • Information about the environment setup when the issue was encountered is included in the issue.
  • Output logs are included in the issue.

What was incorrect, unhelpful, or unexpected?

I can't get VSCODE debugger to stop at any of my breakpoints in my templates/*.html
my launch.json file is:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Django",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}\django_projects\manage.py",
"args": [
"runserver"
],
"django": true,
"justMyCode": false,
"host": "localhost"
}
]
}

What did you expect to see?

A stop in execution at my breakpoint

Output logs

No response

Do you have anything more you want to share?

No response

tutorial part 9 generic editing page layout different from example

The examples shown in tutorial part 9 generic editing templates renders different with the code examples as shown in the tutorial. This might be confusing to novices like me. form.as_table returns the form wrapped in <tr> tags but this needs to be wrapped in an <table> tag for it to be displayed as a table as shown as example. There are no <table> tags in the example code.

Language Class

First off, this is more of a question, not so much an issue, so if there is somewhere else I should be asking please feel free to delete this and re-direct me.

For the association of Language and Book, I understand that a book can be written in multiple languages, so it makes sense to have the foreign key from Language to Book (many books in many languages). However, wouldn't we also want to know what language a particular instance of a book is written in? I'm just confused as to why there is no relationship between Language and BookInstance, or is the fact that we have a foreign key between Book and BookInstance enough to tie in the language of a particular book?

Thanks for any help you can provide!

Issue with test_views.py Author Create View challenge code for Django 2.1 or later

I came across an issue when running tests of the tutorial -Part 10, and to a small extent Part 8 where user permissions are first discussed. I believe this issue arises due to a change in Django 2.1 as indicated on the official documentation page, under the section “Redirecting unauthorized requests in class-based views”, which can be found here.

Current functionality (Django 2.1+):

Authenticated users are denied access with an HTTP 403 Forbidden response.

Old functionality:

In older versions, authenticated users who lacked permissions were redirected to the login page (which resulted in a loop) instead of receiving an HTTP 403 Forbidden response.

Recommend a change to these lines of testing code as follows (in test_views.py):

def test_redirect_if_logged_in_but_not_correct_permission(self):
    login = self.client.login(username='testuser1', password='12345')
    resp = self.client.get(reverse('author_create') )
    self.assertRedirects(resp, '/accounts/login/?next=/catalog/author/create/' )

I’ve used the following, which simply checks that a 403-Forbidden response is returned as stipulated by Django documentation:

def test_redirect_if_logged_in_but_not_correct_permission(self):
    ...
    self.assertEqual(resp.status_code, 403)

There might be better ways, but I hope this will help out.

Create/Update/Delete author

Sorry to have to say this but not able to hooking the "update" and "delete" pages to the side bar.

Tried putting the url mapping like:

<a href="{% url 'author_update' author.pk %}">Update Author</a> 

in the base template but since then coming up with error:

Reverse for 'author_update' with arguments '('',)' not found

Will somebody please let me know where I going wrong.

tutorial part 9 view form.cleaned_data

I am new to Python and Django so I might be missing something. However in part 9 of the tutorial when creating the view renew_book_librarian function there is this line:

book_instance.due_back = form.cleaned_data['renewal_date']

in the if book_renewal_form.is_valid() evaluation code block. should that not be:

book_instance.due_back = book_renewal_form.cleaned_data['renewal_date']

Missing table tags

First, big thanks for this great tutorial.

In https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Forms#The_template
and as per django docs we still need to provide the <table> tag even if we use form.as_table

  <form action="" method="post">
    {% csrf_token %}
    {{ form.as_table }}
    <input type="submit" value="Submit">
  </form>

should be:

  <form action="" method="post">
    {% csrf_token %}
    <table>{{ form.as_table }}</table>
    <input type="submit" value="Submit">
  </form>

(was trying with django 1.11 and table was not rendered without the <table> tag)

How to enable CORS headers in locallibrary tutorial ?

Hello,
Thanks for providing this tutorial, helping a lot. I'm trying to enable CORS headers (I followed the https://www.stackhawk.com/blog/django-cors-guide/ ) mainly changing the settings.py file :
INSTALLED_APPS = [
...
'corsheaders',
...
]
MIDDLEWARE = [
...,
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...,
]
CORS_ALLOW_ALL_ORIGINS = True

But the response still doesn't include CORS. It seems that whatever I do regarding corsheaders in settings.py, it is overridden by something else .

Thanks in advance for the response !

mismatch of UML design and actual code

Hey,

I see in UML that relationship between Book and Author is ManyToMany but whereas in code catalog/models.py (quoting the code below) it was mentioned that "book can only have one author"

author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True)
# Foreign Key used because book can only have one author, but authors can have multiple books
# Author as a string rather than object because it hasn't been declared yet in file.

Why there is discrepancy ???

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.