repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
PacktPublishing/Web-Development-Projects-with-Django
Chapter07/final/form_project/form_example/apps.py
<gh_stars>10-100 from django.apps import AppConfig class FormExampleConfig(AppConfig): name = 'form_example'
PacktPublishing/Web-Development-Projects-with-Django
Chapter10/final/bookr/bookr/views.py
<filename>Chapter10/final/bookr/bookr/views.py from django.contrib.auth.decorators import login_required from django.shortcuts import render @login_required def profile(request): return render(request, 'profile.html')
PacktPublishing/Web-Development-Projects-with-Django
Chapter01/Exercise1.07/bookr/reviews/views.py
<filename>Chapter01/Exercise1.07/bookr/reviews/views.py from django.shortcuts import render def index(request): name = "world" return render(request, "base.html", {"name": name})
PacktPublishing/Web-Development-Projects-with-Django
Chapter02/Exercise2.07/exercise2.07.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django<filename>Chapter02/Exercise2.07/exercise2.07.py<gh_stars>10-100 #!/usr/bin/env python3 from reviews.models import Publisher publisher = Publisher.objects.get(name='Pocket Books')
PacktPublishing/Web-Development-Projects-with-Django
Chapter14/Exercise14.02/bookr_test/apps.py
from django.apps import AppConfig class BookrTestConfig(AppConfig): name = 'bookr_test'
PacktPublishing/Web-Development-Projects-with-Django
Chapter02/Exercise2.04/exercise2.04.py
<filename>Chapter02/Exercise2.04/exercise2.04.py #!/usr/bin/env python3 from datetime import date from reviews.models import Book, Publisher publisher = Publisher.objects.get(name='Packt Publishing') book = Book.objects.create(title='Advanced Deep Learning with Keras', publication_date=date(2018, 10, 31), ...
PacktPublishing/Web-Development-Projects-with-Django
Chapter12/Exercise12.04/bookr/reviews/api_views.py
from rest_framework import viewsets from rest_framework.pagination import LimitOffsetPagination from .models import Book, Review from .serializers import BookSerializer, ReviewSerializer class BookViewSet(viewsets.ReadOnlyModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer class ...
PacktPublishing/Web-Development-Projects-with-Django
Chapter10/final/bookr/session_info.py
<gh_stars>10-100 import base64 import json import pprint import sys def get_session_dictionary(session_key): binary_key, payload = base64.b64decode(session_key).split(b':', 1) session_dictionary = json.loads(payload.decode()) return session_dictionary if __name__ == '__main__': if len(sys.argv)>1: ...
PacktPublishing/Web-Development-Projects-with-Django
Chapter02/Exercise2.05/exercise2.05.py
<filename>Chapter02/Exercise2.05/exercise2.05.py<gh_stars>10-100 #!/usr/bin/env python3 from reviews.models import Book, BookContributor, Contributor contributor = Contributor.objects.get(first_names='Rowel') book = Book.objects.get(title='Advanced Deep Learning with Keras') book_contributor = BookContributor(book=bo...
PacktPublishing/Web-Development-Projects-with-Django
Chapter02/Exercise2.08/exercise2.08.py
#!/usr/bin/env python3 from reviews.models import Contributor contributors = Contributor.objects.all()
PacktPublishing/Web-Development-Projects-with-Django
Chapter18/final/bookr/bookr/utils.py
import datetime from django.db.models import Count from reviews.models import Review def get_books_read(username): """Get the list of books read by a user. :param: str username for whom the book records should be returned :return: list of dict of books read and date of posting the review """ bo...
PacktPublishing/Web-Development-Projects-with-Django
Chapter18/final/bookr/reviews/admin.py
<filename>Chapter18/final/bookr/reviews/admin.py from django.contrib import admin from .models import Book, Review class BookAdmin(admin.ModelAdmin): model = Book list_display = ('title', 'isbn', 'get_publisher', 'publication_date') search_fields = ['title', 'publisher__name'] def get_publisher(self, obj): ...
PacktPublishing/Web-Development-Projects-with-Django
Chapter15/final/bookr/reviews/tests.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django import os from unittest import mock from django.conf import settings from django.http import HttpRequest from django.test import TestCase from reviews.forms import InstanceForm, PublisherForm, ReviewForm, BookMediaForm from reviews.models import Book from...
PacktPublishing/Web-Development-Projects-with-Django
Chapter08/Exercise8.03/media_project/media_example/tests.py
<filename>Chapter08/Exercise8.03/media_project/media_example/tests.py import os from io import BytesIO from urllib.request import urlopen from django.conf import settings from django.test import LiveServerTestCase, Client class Exercise3Test(LiveServerTestCase): def test_media_example_upload(self): """ ...
PacktPublishing/Web-Development-Projects-with-Django
Chapter02/Exercise2.13/exercise2.13.py
#!/usr/bin/env python3 from reviews.models import Contributor Contributor.objects.filter(last_names='Tyrrell').update(first_names='Mike') Contributor.objects.get(last_names='Tyrrell').first_names
PacktPublishing/Web-Development-Projects-with-Django
Chapter11/Exercise11.01/filter_demo/views.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django from django.shortcuts import render def index(request): names = "john,doe,mark,swain" return render(request, "index.html", {'names': names})
PacktPublishing/Web-Development-Projects-with-Django
Chapter08/Exercise8.04/media_project/media_example/forms.py
from django import forms class UploadForm(forms.Form): file_upload = forms.FileField()
PacktPublishing/Web-Development-Projects-with-Django
Chapter12/Exercise12.02/bookr/reviews/api_views.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django from rest_framework.decorators import api_view from rest_framework.response import Response from .models import Book from .serializers import BookSerializer @api_view() def all_books(request): books = Book.objects.all() book_serializer = BookSeri...
PacktPublishing/Web-Development-Projects-with-Django
Chapter10/Exercise10.02/bookr_admin/apps.py
<gh_stars>10-100 from django.contrib.admin.apps import AdminConfig class BookrAdminConfig(AdminConfig): default_site = 'bookr_admin.admin.BookrAdmin'
PacktPublishing/Web-Development-Projects-with-Django
Chapter13/Exercise13.01/csv_reader.py
import csv def read_csv(filename): """Read and output the details of CSV file.""" try: with open(filename, newline='') as csv_file: csv_reader = csv.reader(csv_file) for record in csv_reader: print(record) except (IOError, OSError) as file_read_error: prin...
PacktPublishing/Web-Development-Projects-with-Django
Chapter11/Exercise11.02/filter_demo/views.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django from django.shortcuts import render def index(request): names = "john,doe,mark,swain" return render(request, "index.html", {'name': names}) def greeting_view(request): return render(request, 'simple_tag_template.html', {'username': 'jdoe'})
PacktPublishing/Web-Development-Projects-with-Django
Chapter11/Exercise11.04/book_management/urls.py
from django.urls import path from .views import BookRecordFormView, FormSuccessView urlpatterns = [ path('new_book_record', BookRecordFormView.as_view(), name='book_record_form'), path('entry_success', FormSuccessView.as_view(), name='form_success') ]
PacktPublishing/Web-Development-Projects-with-Django
Chapter15/Exercise15.03/bookr/reviews/tests.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django import os from django.conf import settings from django.test import TestCase class Exercise3Test(TestCase): def test_djdt_setup(self): """Test that the configuration for Django Debug Toolbar is correct.""" self.assertIn('debug_toolbar....
PacktPublishing/Web-Development-Projects-with-Django
Chapter15/Exercise15.01/bookr/reviews/tests.py
<gh_stars>10-100 from configurations import Configuration, values from django.test import TestCase from bookr import settings as direct_settings class Exercise1Test(TestCase): def test_configurations_refactoring(self): """Import the settings file directly to check that the Dev/Prod classes have been conf...
PacktPublishing/Web-Development-Projects-with-Django
Chapter07/Exercise7.01/form_project/form_example/forms.py
from django import forms from django.core.exceptions import ValidationError def validate_email_domain(value): if value.split("@")[-1].lower() != "example.com": raise ValidationError("The email address must be on the domain example.com.") class OrderForm(forms.Form): magazine_count = forms.IntegerFie...
PacktPublishing/Web-Development-Projects-with-Django
Chapter03/Exercise3.04/bookr/reviews/models.py
from django.contrib import auth from django.db import models class Publisher(models.Model): """A company that publishes books.""" name = models.CharField(max_length=50, help_text="The name of the Publisher.") website = models.URLField(help_text="The Publisher's website.") e...
PacktPublishing/Web-Development-Projects-with-Django
Chapter06/Exercise6.01/form_project/form_example/views.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django<gh_stars>10-100 from django.shortcuts import render def form_example(request): return render(request, "form-example.html")
PacktPublishing/Web-Development-Projects-with-Django
Chapter02/Activity2.01/juggler/projectm/migrations/0002_auto_20200108_1834.py
# Generated by Django 3.0.2 on 2020-01-08 18:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('projectm', '0001_initial'), ] operations = [ migrations.AlterField( model_name='task', name='completed', ...
PacktPublishing/Web-Development-Projects-with-Django
Chapter12/Activity12.01/bookr/reviews/api_views.py
from rest_framework import generics from .models import Book, Contributor from .serializers import BookSerializer, ContributorSerializer class AllBooks(generics.ListAPIView): queryset = Book.objects.all() serializer_class = BookSerializer class ContributorView(generics.ListAPIView): queryset = Contribu...
PacktPublishing/Web-Development-Projects-with-Django
Chapter14/Exercise14.02/bookr_test/tests.py
from django.test import TestCase from .models import Publisher class TestPublisherModel(TestCase): """Test the publisher model.""" def setUp(self): self.p = Publisher(name='Packt', website='www.packt.com', email='<EMAIL>') def test_create_publisher(self): self.assertIsInstance(self.p, Pub...
PacktPublishing/Web-Development-Projects-with-Django
Chapter03/Exercise3.01/bookr/reviews/views.py
from django.http import HttpResponse from .models import Book def welcome_view(request): message = f"<html><h1>Welcome to Bookr!</h1> <p>{Book.objects.count()} books and counting!</p></html>" return HttpResponse(message)
PacktPublishing/Web-Development-Projects-with-Django
Chapter01/Exercise1.03/bookr/reviews/tests.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django<filename>Chapter01/Exercise1.03/bookr/reviews/tests.py from django.test import TestCase from django.test import Client class Exercise3TestCase(TestCase): def test_index_view(self): """Test that the index view returns Hello, world!""" c...
PacktPublishing/Web-Development-Projects-with-Django
Chapter01/Exercise1.07/bookr/reviews/tests.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django<filename>Chapter01/Exercise1.07/bookr/reviews/tests.py<gh_stars>10-100 from django.test import TestCase from django.test import Client class Exercise7TestCase(TestCase): def test_template_render(self): """Test that the index view now returns t...
PacktPublishing/Web-Development-Projects-with-Django
Chapter05/Exercise5.01/business_site/landing/tests.py
import os from urllib.request import urlopen from django.conf import settings from django.contrib.staticfiles.testing import StaticLiveServerTestCase class Exercise1Test(StaticLiveServerTestCase): """ These tests use `StaticLiveServerTestCase` and `urlopen` since the normal `TestCase` uses a special server t...
PacktPublishing/Web-Development-Projects-with-Django
Chapter05/final/business_site/landing/tests.py
<gh_stars>10-100 from django.conf import settings from django.test import TestCase class Exercise6Test(TestCase): """ This has only one test. We assume if we got to this point and the other exercises were OK we don't need to test Django's ManifestFileStorage. Just that it has been set properly. """ ...
PacktPublishing/Web-Development-Projects-with-Django
Chapter13/Activity13.01/bookr/bookr/views.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render from plotly.offline import plot import plotly.graph_objects as graphs from io import BytesIO import xlsxwriter from .utils ...
PacktPublishing/Web-Development-Projects-with-Django
Chapter10/Exercise10.01/bookr_admin/admin.py
from django.contrib import admin from django.contrib.auth.admin import User class BookrAdmin(admin.AdminSite): site_header = "Bookr Administration" admin_site = BookrAdmin(name='bookr_admin') admin_site.register(User)
PacktPublishing/Web-Development-Projects-with-Django
Chapter13/Exercise13.02/csv_writer.py
import csv def write_csv(filename, header, data): """Write the provided data to the CSV file. :param str filename: The name of the file to which the data should be written :param list header: The header for the columns in csv file :param list data: The list of list mapping the values to the columns ...
PacktPublishing/Web-Development-Projects-with-Django
Chapter06/Exercise6.02/form_project/form_example/views.py
<gh_stars>10-100 from django.shortcuts import render def form_example(request): for name in request.POST: print("{}: {}".format(name, request.POST.getlist(name))) return render(request, "form-example.html", {"method": request.method})
PacktPublishing/Web-Development-Projects-with-Django
Chapter12/final/bookr/bookr/views.py
<filename>Chapter12/final/bookr/bookr/views.py from django.contrib.auth.decorators import login_required from django.shortcuts import render @login_required def profile(request): user = request.user permissions = user.get_all_permissions() return render(request, 'profile.html', {'user': user, '...
PacktPublishing/Web-Development-Projects-with-Django
Chapter08/Exercise8.02/media_project/media_example/views.py
<filename>Chapter08/Exercise8.02/media_project/media_example/views.py from django.shortcuts import render def media_example(request): return render(request, "media-example.html")
PacktPublishing/Web-Development-Projects-with-Django
Chapter02/Exercise2.10/exercise2.10.py
<gh_stars>10-100 #!/usr/bin/env python3 from reviews.models import Contributor Contributor.objects.filter(book__title='The Talisman')
PacktPublishing/Web-Development-Projects-with-Django
Chapter08/Exercise8.03/media_project/media_example/views.py
import os from django.conf import settings from django.shortcuts import render def media_example(request): if request.method == 'POST': save_path = os.path.join(settings.MEDIA_ROOT, request.FILES["file_upload"].name) with open(save_path, "wb") as output_file: for chunk in request.FILE...
PacktPublishing/Web-Development-Projects-with-Django
Chapter02/Exercise2.02/exercise2.02.py
#!/usr/bin/env python3 from reviews.models import Publisher publisher = Publisher(name='<NAME>', website='https://www.packtpub.com', email='<EMAIL>') publisher.save() publisher.email = '<EMAIL>' publisher.save()
PacktPublishing/Web-Development-Projects-with-Django
Chapter08/Activity8.01/bookr/reviews/tests.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django import os from unittest import mock from PIL import Image from django import forms from django.conf import settings from django.test import TestCase, Client from django.utils import timezone from reviews.forms import BookMediaForm from reviews.models impo...
PacktPublishing/Web-Development-Projects-with-Django
Chapter18/final/bookr/bookr_admin/admin.py
from django.contrib import admin from django.utils.translation import gettext as _ from reviews.models import Book class BooksAdmin(admin.ModelAdmin): model = Book list_display = ('title', 'isbn', 'get_publisher') search_fields = ['title', 'publisher__name'] def get_publisher(self, obj): return obj.publis...
PacktPublishing/Web-Development-Projects-with-Django
Chapter15/Exercise15.04/bookr/reviews/tests.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django import os from django.conf import settings from django.test import TestCase, Client class Exercise4Test(TestCase): def test_crispy_settings(self): """Test that the right settings are configured for Django Crispy Forms.""" self.assertI...
PacktPublishing/Web-Development-Projects-with-Django
Chapter02/Exercise2.14/exercise2.14.py
<gh_stars>10-100 #!/usr/bin/env python3 from reviews.models import Contributor Contributor.objects.get(last_names='Wharton').delete() Contributor.objects.get(last_names='Wharton')
PacktPublishing/Web-Development-Projects-with-Django
Chapter14/Exercise14.04/bookr_test/urls.py
<filename>Chapter14/Exercise14.04/bookr_test/urls.py from django.urls import path from . import views urlpatterns = [ path('test/greeting', views.greeting_view, name='greeting_view'), path('test/greet_user', views.greeting_view_user, name='greeting_view_user') ]
PacktPublishing/Web-Development-Projects-with-Django
Chapter18/final/bookr/reviews/migrations/0003_auto_20191227_0751.py
<gh_stars>10-100 # Generated by Django 3.0a1 on 2019-12-27 07:51 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('reviews', '0002_auto_20191007_0112'), ] operations = [ migrations.AlterField( ...
PacktPublishing/Web-Development-Projects-with-Django
Chapter10/final/bookr/reviews/utils.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django def average_rating(rating_list): if not rating_list: return 0 return round(sum(rating_list) / len(rating_list))
PacktPublishing/Web-Development-Projects-with-Django
Chapter14/Exercise14.03/bookr_test/urls.py
<gh_stars>10-100 from django.urls import path from . import views urlpatterns = [ path('test/greeting', views.greeting_view, name='greeting_view') ]
PacktPublishing/Web-Development-Projects-with-Django
Chapter07/Activity7.01/bookr/reviews/tests.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django import re from django.test import Client from django.test import TestCase from reviews.models import Publisher class Activity1Test(TestCase): def test_container_wrapper(self): """The <div class="container-fluid"> should have been added.""" ...
PacktPublishing/Web-Development-Projects-with-Django
Chapter02/Exercise2.09/exercise2.09.py
#!/usr/bin/env python3 from reviews.models import Contributor Contributor.objects.create(first_names='Peter', last_names='Wharton', email='<EMAIL>') Contributor.objects.create(first_names='Peter', last_names='Tyrrell', email='<EMAIL>') contributors = Contributor.objects.filter(first_names='Peter') Contributor.objects...
PacktPublishing/Web-Development-Projects-with-Django
Chapter18/final/bookr/reviews/serializers.py
from django.contrib.auth.models import User from django.utils import timezone from rest_framework import serializers from rest_framework.exceptions import NotAuthenticated, PermissionDenied from .models import Book, Publisher, Review from .utils import average_rating class PublisherSerializer(serializers.ModelSerial...
PacktPublishing/Web-Development-Projects-with-Django
Chapter11/Exercise11.02/filter_demo/urls.py
<gh_stars>10-100 from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('greet', views.greeting_view, name='greeting') ]
PacktPublishing/Web-Development-Projects-with-Django
Chapter07/final/bookr/reviews/forms.py
<gh_stars>10-100 from django import forms from .models import Publisher, Review class SearchForm(forms.Form): search = forms.CharField(required=False, min_length=3) search_in = forms.ChoiceField(required=False, choices=( ("title", "Title...
PacktPublishing/Web-Development-Projects-with-Django
Chapter02/Exercise2.11/exercise2.11.py
#!/usr/bin/env python3 from reviews.models import Book book = Book.objects.get(title='The Talisman') book.contributors.all()
PacktPublishing/Web-Development-Projects-with-Django
Chapter02/Exercise2.12/exercise2.12.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django<filename>Chapter02/Exercise2.12/exercise2.12.py #!/usr/bin/env python3 from reviews.models import Contributor contributor = Contributor.objects.get(first_names='Rowel') contributor.book_set.all()
PacktPublishing/Web-Development-Projects-with-Django
Chapter08/Exercise8.01/media_project/media_example/tests.py
import os from urllib.request import urlopen from django.conf import settings from django.test import LiveServerTestCase class Exercise1Test(LiveServerTestCase): def test_media_serving(self): """Test that our test.txt file can be retrieved using the media URL.""" media_root = settings.MEDIA_ROOT ...
PacktPublishing/Web-Development-Projects-with-Django
Chapter18/final/bookr/reviews/tests.py
import os import re from django.conf import settings from django.test import TestCase, Client class Activity1Test(TestCase): def test_cleanup(self): """Test that the files, view, etc from the previous exercises have been removed/""" self.assertFalse(os.path.exists(os.path.join(settings.BASE_DIR, ...
PacktPublishing/Web-Development-Projects-with-Django
Chapter02/Exercise2.06/exercise2.06.py
#!/usr/bin/env python3 from reviews.models import Book, Contributor contributor = Contributor.objects.create(first_names='Packt', last_names='<NAME>', email='<EMAIL>') book = Book.objects.get(title="Advanced Deep Learning with Keras") book.contributors.add(contributor, through_defaults={'role': 'EDITOR'})
PacktPublishing/Web-Development-Projects-with-Django
Chapter14/Exercise14.04/bookr_test/tests.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django from django.test import TestCase, Client from django.contrib.auth.models import User from .models import Publisher class TestPublisherModel(TestCase): """Test the publisher model.""" def setUp(self): self.p = Publisher(name='Packt', websi...
PacktPublishing/Web-Development-Projects-with-Django
Chapter08/Exercise8.06/media_project/media_example/tests.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django from unittest import mock import os from django import forms from django.conf import settings from django.test import LiveServerTestCase, Client from urllib.request import urlopen from media_example.forms import UploadForm from media_example.views import ...
PacktPublishing/Web-Development-Projects-with-Django
Chapter04/final/comment8or/messageboard/apps.py
from django.apps import AppConfig from django.contrib.admin.apps import AdminConfig class MessageboardConfig(AppConfig): name = 'messageboard' class MessageboardAdminConfig(AdminConfig): default_site = 'admin.Comment8orAdminSite'
PacktPublishing/Web-Development-Projects-with-Django
Chapter18/final/bookr/reviews/api_views.py
from django.contrib.auth import authenticate from rest_framework import viewsets from rest_framework.authentication import TokenAuthentication from rest_framework.authtoken.models import Token from rest_framework.pagination import LimitOffsetPagination from rest_framework.permissions import IsAuthenticated from rest_fr...
PacktPublishing/Web-Development-Projects-with-Django
Chapter12/Exercise12.02/bookr/reviews/serializers.py
<gh_stars>10-100 from rest_framework import serializers class PublisherSerializer(serializers.Serializer): name = serializers.CharField() website = serializers.URLField() email = serializers.EmailField() class BookSerializer(serializers.Serializer): title = serializers.CharField() publication_da...
PacktPublishing/Web-Development-Projects-with-Django
Chapter15/Exercise15.01/bookr/env_example.py
import os # This will set the value since it's not already set os.environ.setdefault('UNSET_VAR', 'UNSET_VAR_VALUE') # This value will not be set since it's already passed # in from the command line os.environ.setdefault('SET_VAR', 'SET_VAR_VALUE') print('UNSET_VAR:' + os.environ.get('UNSET_VAR', '')) print('SET_VA...
PacktPublishing/Web-Development-Projects-with-Django
Chapter01/Exercise1.01/bookr/reviews/tests.py
<filename>Chapter01/Exercise1.01/bookr/reviews/tests.py from django.test import TestCase from django.test import Client class Exercise1TestCase(TestCase): def test_admin_get(self): """ Test that we can make a request, we use /admin since it's the only URL map set up by default. This at lea...
PacktPublishing/Web-Development-Projects-with-Django
Chapter10/Exercise10.04/bookr_admin/admin.py
from django.contrib import admin from django.template.response import TemplateResponse from django.urls import path class BookrAdmin(admin.AdminSite): site_header = "Bookr Administration" def profile_view(self, request): request.current_app = self.name context = self.each_context(request) ...
PacktPublishing/Web-Development-Projects-with-Django
Chapter14/Exercise14.02/bookr_test/models.py
from django.db import models class Publisher(models.Model): """A company that publishes books.""" name = models.CharField(max_length=50, help_text="The name of the Publisher.") website = models.URLField(help_text="The Publisher's website.") email = models.EmailField(help_tex...
PacktPublishing/Web-Development-Projects-with-Django
Chapter13/Exercise13.06/bookr/bookr/views.py
from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render from plotly.offline import plot import plotly.graph_objects as graphs from io import BytesIO import xlsxwriter from .utils import get_books_read, get_books_read_by_month @login_require...
PacktPublishing/Web-Development-Projects-with-Django
Chapter12/Activity12.01/bookr/reviews/serializers.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django<filename>Chapter12/Activity12.01/bookr/reviews/serializers.py from rest_framework import serializers from .models import Book, Publisher, BookContributor, Contributor class PublisherSerializer(serializers.ModelSerializer): class Meta: model =...
PacktPublishing/Web-Development-Projects-with-Django
Chapter11/Exercise11.04/book_management/models.py
from django.db import models class Book(models.Model): name = models.CharField(max_length=255) author = models.CharField(max_length=50)
PacktPublishing/Web-Development-Projects-with-Django
Chapter01/Exercise1.06/bookr/reviews/tests.py
<filename>Chapter01/Exercise1.06/bookr/reviews/tests.py from django.test import TestCase from django.test import Client class Exercise6TestCase(TestCase): def test_template_render(self): """Test that the index view now returns the rendered template.""" c = Client() response = c.get('/') ...
PacktPublishing/Web-Development-Projects-with-Django
Chapter13/Exercise13.03/xlsx_demo.py
<gh_stars>10-100 import xlsxwriter def create_workbook(filename): """Create a new workbook on which we can work.""" workbook = xlsxwriter.Workbook(filename) return workbook def create_worksheet(workbook): """Add a new worksheet in the workbook.""" worksheet = workbook.add_worksheet() return wo...
PacktPublishing/Web-Development-Projects-with-Django
Chapter05/final/bookr/reviews/tests.py
import os from urllib.request import urlopen from django.conf import settings from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.test import Client def read_content(path): with open(path) as f: return f.read() class Activity3Test(StaticLiveServerTestCase): """ T...
PacktPublishing/Web-Development-Projects-with-Django
Chapter18/final/bookr/reviews/migrations/0005_delete_examplemodel.py
<gh_stars>10-100 # Generated by Django 3.0 on 2020-01-23 22:47 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('reviews', '0004_examplemodel'), ] operations = [ migrations.DeleteModel( name='ExampleModel', ), ]
PacktPublishing/Web-Development-Projects-with-Django
Chapter08/final/media_project/media_example/tests.py
from unittest import mock import os from django import forms from django.conf import settings from django.test import LiveServerTestCase, Client from media_example.forms import UploadForm from media_example.models import ExampleModel from media_example.views import media_example from urllib.request import urlopen cl...
PacktPublishing/Web-Development-Projects-with-Django
Chapter04/final/comment8or/admin.py
<filename>Chapter04/final/comment8or/admin.py from django.contrib import admin class Comment8orAdminSite(admin.AdminSite): index_title = 'c8admin' title_header = 'c8 site admin' site_header = 'c8admin' logout_template = 'comment8or/logged_out.html'
PacktPublishing/Web-Development-Projects-with-Django
Chapter13/Exercise13.04/pdf_demo.py
from weasyprint import HTML def generate_pdf(url, pdf_file): """Generate PDF version of the provided URL.""" print("Generating PDF...") HTML(url).write_pdf(pdf_file) if __name__ == '__main__': url = 'http://text.npr.org' pdf_file = 'demo_page.pdf' generate_pdf(url, pdf_file)
PacktPublishing/Web-Development-Projects-with-Django
Chapter14/Exercise14.04/bookr_test/views.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django<gh_stars>10-100 from django.http import HttpResponse from django.contrib.auth.decorators import login_required def greeting_view(request): """Greet the user.""" return HttpResponse("Hey there, welcome to Bookr! Your one stop place to review books....
PacktPublishing/Web-Development-Projects-with-Django
Chapter13/Exercise13.05/scatter_plot_demo.py
<filename>Chapter13/Exercise13.05/scatter_plot_demo.py from plotly.offline import plot import plotly.graph_objs as graphs def generate_scatter_plot(x_axis, y_axis): """Generate a scatter plot for the provided x and y-axis values.""" figure = graphs.Figure() scatter = graphs.Scatter(x=x_axis, y=y_axis) ...
PacktPublishing/Web-Development-Projects-with-Django
Chapter14/Exercise14.03/bookr_test/views.py
<gh_stars>10-100 from django.http import HttpResponse def greeting_view(request): """Greet the user.""" return HttpResponse("Hey there, welcome to Bookr! Your one stop place to review books.")
PacktPublishing/Web-Development-Projects-with-Django
Chapter08/final/media_project/media_example/apps.py
from django.apps import AppConfig class MediaExampleConfig(AppConfig): name = 'media_example'
PacktPublishing/Web-Development-Projects-with-Django
Chapter06/Exercise6.02/form_project/form_example/tests.py
import re from django.http import HttpRequest, QueryDict from django.test import TestCase from django.test import Client from unittest import mock from form_example.views import form_example class Exercise2Test(TestCase): def test_fields_in_view(self): """"Test that all the fields we defined appear in ...
PacktPublishing/Web-Development-Projects-with-Django
Chapter18/final/bookr/reviews/utils.py
def average_rating(rating_list): return round(sum(rating_list)/len(rating_list))
PacktPublishing/Web-Development-Projects-with-Django
Chapter01/Exercise1.05/bookr/reviews/tests.py
<filename>Chapter01/Exercise1.05/bookr/reviews/tests.py import os from django.test import TestCase from django.conf import settings class Exercise5TestCase(TestCase): def test_template_content(self): """Test that base.html exists and has the expected content""" template_path = os.path.join(settin...
PacktPublishing/Web-Development-Projects-with-Django
Chapter10/final/bookr/bookr_admin/admin.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django from django.contrib import admin class BookrAdmin(admin.AdminSite): site_header = "Bookr Administration Portal" site_title = "Bookr Administration Portal" index_title = "Bookr Administration"
PacktPublishing/Web-Development-Projects-with-Django
Chapter01/Exercise1.04/bookr/reviews/views.py
<filename>Chapter01/Exercise1.04/bookr/reviews/views.py from django.http import HttpResponse def index(request): name = request.GET.get("name") or "world" return HttpResponse("Hello, {}!".format(name))
PacktPublishing/Web-Development-Projects-with-Django
Chapter02/Activity2.01/juggler/projectm/models.py
<reponame>PacktPublishing/Web-Development-Projects-with-Django from django.db import models class Project(models.Model): name = models.CharField(max_length=50, help_text="Project Name") creation_time = models.DateTimeField(auto_now_add=True, help_text="Project creation time.") completion_time = models.Dat...
Kamatera/salt-cloud-module-kamatera
tests/e2e_test.py
<filename>tests/e2e_test.py import json import os import subprocess testsdir = os.path.dirname(__file__) outputdir = os.path.abspath(os.path.join(testsdir, "output")) os.makedirs(outputdir, exist_ok=True) os.makedirs("/etc/salt/cloud.providers.d", exist_ok=True) if os.path.exists("/etc/salt/cloud.providers.d/cloudcli...
Kamatera/salt-cloud-module-kamatera
salt_cloud_module_kamatera/loader.py
import os PKG_DIR = os.path.abspath(os.path.dirname(__file__)) def clouds_dirs(): yield os.path.join(PKG_DIR, 'clouds')
Kamatera/salt-cloud-module-kamatera
setup.py
<reponame>Kamatera/salt-cloud-module-kamatera from setuptools import setup, find_packages with open("README.md", "r") as f: long_description = f.read() setup( name="salt_cloud_module_kamatera", version="0.0.0", packages=find_packages(exclude=['tests',]), install_requires=["salt>=2019.2.0"], ...
vovanbo/django-cms
cms/test_utils/project/mti_pluginapp/models.py
# -*- coding: utf-8 -*- from django.db import models from cms.models import CMSPlugin class TestPluginAlphaModel(CMSPlugin): """ Nothing interesting here, move along. """ alpha = models.CharField('name', blank=False, default='test plugin alpha', max_length=32) def get_add_url(self): ret...
vovanbo/django-cms
cms/test_utils/project/extensionapp/models.py
# -*- coding: utf-8 -*- from django.conf import settings from django.db import models from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) favor...
vovanbo/django-cms
cms/tests/test_wizards.py
# -*- coding: utf-8 -*- from django import forms from django.core.exceptions import ImproperlyConfigured from django.forms.models import ModelForm from django.utils.encoding import smart_text from django.utils.translation import ugettext as _ from cms.api import create_page from cms.constants import TEMPLATE_INHERITA...
vovanbo/django-cms
cms/migrations/0012_auto_20150607_2207.py
<reponame>vovanbo/django-cms # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('cms', '0011_auto_20150419_1006'), ] operations = [ migrations....
vovanbo/django-cms
cms/wizards/urls.py
# -*- coding: utf-8 -*- from django.conf.urls import patterns, url from .views import WizardCreateView urlpatterns = patterns('', # NOQA url(r"^create/$", WizardCreateView.as_view(), name="cms_wizard_create"), )
vovanbo/django-cms
cms/apps.py
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ from cms.utils.setup import setup class CMSConfig(AppConfig): name = 'cms' verbose_name = _("django CMS") def ready(self): setup()