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),
isbn='9781788629416', publisher=publisher)
|
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 ReviewViewSet(viewsets.ModelViewSet):
queryset = Review.objects.order_by('-date_created')
serializer_class = ReviewSerializer
pagination_class = LimitOffsetPagination
authentication_classes = []
|
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:
session_key = sys.argv[1]
session_dictionary = get_session_dictionary(session_key)
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(session_dictionary)
|
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=book, contributor=contributor, role='AUTHOR')
book_contributor.save() |
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
"""
books = Review.objects.filter(creator__username__contains=username).all()
return [{'title': book_read.book.title, 'completed_on': book_read.date_created} for book_read in books]
def get_books_read_by_month(username):
"""Get the books read by the user on per month basis.
:param: str The username for which the books needs to be returned
:return: dict of month wise books read
"""
current_year = datetime.datetime.now().year
books = Review.objects.filter(creator__username__contains=username,date_created__year=current_year).values('date_created__month').annotate(book_count=Count('book__title'))
return books
|
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):
return obj.publisher.name
admin.site.register(Book, BookAdmin)
admin.site.register(Review)
|
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 reviews.views import book_media
class Activity1Test(TestCase):
def test_crispy_form_used_in_template(self):
"""Test that the {% crispy %} template tag is being used to render the form in search-results.html"""
with open(os.path.join(settings.BASE_DIR, 'reviews/templates/reviews/instance-form.html')) as tf:
template_content = tf.read()
self.assertIn('{% load crispy_forms_tags %', template_content)
self.assertIn('{% crispy form %}', template_content)
self.assertNotIn('<form', template_content)
self.assertNotIn('</form>', template_content)
def test_form_helper(self):
"""
Test that InstanceForm has a helper with a submit button, the button text changes based on the existence of the
instance argument. We can't test this on InstanceForm directly since it can't be instantiated without a model.
Instead run the same test on each form that inherits from it, then check their inheritance.
"""
for form_class in (PublisherForm, ReviewForm, BookMediaForm):
form = form_class()
self.assertEquals(form.helper.form_method, 'post')
self.assertEquals(form.helper.inputs[0].value, 'Create')
form_with_instance = form_class(instance=form_class.Meta.model())
self.assertEquals(form_with_instance.helper.form_method, 'post')
self.assertEquals(form_with_instance.helper.inputs[0].value, 'Save')
self.assertTrue(issubclass(form_class, InstanceForm))
@mock.patch('reviews.views.render')
@mock.patch('reviews.views.BookMediaForm')
def test_book_media_render_call(self, mock_book_media_form, mock_render):
"""Test that the `render` call in book_media no longer contains `is_file_upload` item."""
req = mock.MagicMock(spec=HttpRequest, name='request')
req.user = mock.MagicMock()
req.user.is_authenticated = True
req.method = 'GET'
mock_book = mock.MagicMock(spec=Book, name='book')
with mock.patch('reviews.views.get_object_or_404', return_value=mock_book) as mock_get_object_or_404:
resp = book_media(req, 3)
mock_render.assert_called_with(req, 'reviews/instance-form.html',
{'instance': mock_book, 'form': mock_book_media_form.return_value,
'model_type': 'Book'})
|
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):
"""
Test the upload functionality to the media_example view. Check it can be downloaded again.
"""
test_data = b'some test data'
filename = 'exercise_3_test.txt'
save_path = os.path.join(settings.MEDIA_ROOT, filename)
fp = BytesIO(test_data)
fp.name = filename
try:
c = Client()
resp = c.post('/media-example/', {'file_upload': fp})
self.assertEquals(resp.status_code, 200)
with open(save_path, 'rb') as uploaded_fp:
self.assertEquals(uploaded_fp.read(), test_data)
media_file = urlopen(self.live_server_url + '/media/' + filename)
self.assertEquals(media_file.read(), test_data)
finally:
if os.path.exists(save_path):
os.unlink(save_path)
|
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 = BookSerializer(books, many=True)
return Response(book_serializer.data)
|
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:
print("Unable to open the csv file. Exception: {}".format(file_read_error))
if __name__ == '__main__':
read_csv('market_cap.csv')
|
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.middleware.DebugToolbarMiddleware', settings.MIDDLEWARE)
self.assertIn('debug_toolbar', settings.INSTALLED_APPS)
self.assertEquals(['127.0.0.1'], settings.INTERNAL_IPS)
def test_djdt_urls(self):
"""
Test that the DJDT Urls are set up. This is a manual process since DjDT won't render for the test Client,
and tests run with DEBUG=True so the urlpatterns won't contain the path. This might be a bit fragile.
"""
with open(os.path.join(settings.BASE_DIR, 'bookr/urls.py')) as sf:
self.assertIn(" path('__debug__/', include(debug_toolbar.urls))", sf.read())
|
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 configured."""
self.assertTrue(issubclass(direct_settings.Dev, Configuration))
self.assertTrue(issubclass(direct_settings.Prod, direct_settings.Dev))
# since we are running in DEBUG mode we can't check how these values were set
self.assertTrue(direct_settings.Dev.DEBUG)
self.assertEqual(direct_settings.Dev.ALLOWED_HOSTS, [])
self.assertIsInstance(direct_settings.Dev.SECRET_KEY, str)
# since we are running in DEBUG mode we can check how the values were set on the non-active conf
self.assertFalse(direct_settings.Prod.DEBUG)
self.assertIsInstance(direct_settings.Prod.ALLOWED_HOSTS, values.ListValue)
self.assertIsInstance(direct_settings.Prod.SECRET_KEY, values.SecretValue)
|
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.IntegerField(min_value=0, max_value=80)
book_count = forms.IntegerField(min_value=0, max_value=50)
send_confirmation = forms.BooleanField(required=False)
email = forms.EmailField(required=False, validators=[validate_email_domain])
def clean_email(self):
return self.cleaned_data['email'].lower()
def clean(self):
cleaned_data = super().clean()
if cleaned_data["send_confirmation"] and not cleaned_data.get("email"):
self.add_error("email", "Please enter an email address to receive the confirmation message.")
elif cleaned_data.get("email") and not cleaned_data["send_confirmation"]:
self.add_error("send_confirmation", "Please check this if you want to receive a confirmation email.")
item_total = cleaned_data.get("magazine_count", 0) + cleaned_data.get("book_count", 0)
if item_total > 100:
self.add_error(None, "The total number of items must be 100 or less.")
|
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.")
email = models.EmailField(help_text="The Publisher's email address.")
def __str__(self):
return self.name
class Book(models.Model):
"""A published book."""
title = models.CharField(max_length=70,
help_text="The title of the book.")
publication_date = models.DateField(
verbose_name="Date the book was published.")
isbn = models.CharField(max_length=20,
verbose_name="ISBN number of the book.")
publisher = models.ForeignKey(Publisher,
on_delete=models.CASCADE)
contributors = models.ManyToManyField('Contributor',
through="BookContributor")
def __str__(self):
return self.title
class Contributor(models.Model):
"""A contributor to a Book, e.g. author, editor, co-author."""
first_names = models.CharField(max_length=50,
help_text="The contributor's first name or names.")
last_names = models.CharField(max_length=50,
help_text="The contributor's last name or names.")
email = models.EmailField(help_text="The contact email for the contributor.")
def __str__(self):
return self.first_names
class BookContributor(models.Model):
class ContributionRole(models.TextChoices):
AUTHOR = "AUTHOR", "Author"
CO_AUTHOR = "CO_AUTHOR", "Co-Author"
EDITOR = "EDITOR", "Editor"
book = models.ForeignKey(Book, on_delete=models.CASCADE)
contributor = models.ForeignKey(Contributor, on_delete=models.CASCADE)
role = models.CharField(verbose_name="The role this contributor had in the book.",
choices=ContributionRole.choices, max_length=20)
class Review(models.Model):
content = models.TextField(help_text="The Review text.")
rating = models.IntegerField(help_text="The the reviewer has given.")
date_created = models.DateTimeField(auto_now_add=True,
help_text="The date and time the review was created.")
date_edited = models.DateTimeField(null=True,
help_text='''The date and time the review was last edited.'''
)
creator = models.ForeignKey(auth.get_user_model(), on_delete=models.CASCADE)
book = models.ForeignKey(Book, on_delete=models.CASCADE,
help_text="The Book that this review is for.")
|
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',
field=models.BooleanField(default=False, help_text='Task completion status'),
),
]
|
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 = Contributor.objects.all()
serializer_class = ContributorSerializer
|
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, Publisher)
def test_str_representation(self):
self.assertEquals(str(self.p), "Packt")
|
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 = Client()
response = c.get('/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'Hello, world!')
|
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 the rendered template."""
c = Client()
response = c.get('/')
self.assertIn(b'<title>Title</title>', response.content) # check that it is HTML
self.assertIn(b'Hello, world!', response.content)
|
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 that does
not serve static assets.
"""
def test_django_conf(self):
"""Check that `landing` is in `settings.INSTALLED_APPS` and that the static dir is not manually defined."""
self.assertIn('landing', settings.INSTALLED_APPS)
self.assertEquals(0, len(settings.STATICFILES_DIRS))
def test_logo_get(self):
"""
Test that the logo.png can be downloaded, and the content matches that on disk. This also checks the logo.png is
in the right location and is being served using the static files finder.
"""
response = urlopen(self.live_server_url + '/static/landing/logo.png').read()
current_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(current_dir, 'static', 'landing', 'logo.png'), 'rb') as f:
self.assertEqual(response, f.read())
|
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.
"""
def test_django_conf(self):
"""
Check that `landing` is in `settings.INSTALLED_APPS`, the static dir is set to <projectdir>/static, and
STATIC_ROOT is set to the static_production_test directory, amd that STATICFILES_STORAGE is set to
'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
"""
self.assertIn('landing', settings.INSTALLED_APPS)
self.assertEquals([settings.BASE_DIR + '/static'], settings.STATICFILES_DIRS)
self.assertEquals(settings.BASE_DIR + '/static_production_test', settings.STATIC_ROOT)
self.assertEquals(
settings.STATICFILES_STORAGE, 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage')
|
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 import get_books_read, get_books_read_by_month
@login_required
def profile(request):
user = request.user
permissions = user.get_all_permissions()
# Get the books read in different months this year
books_read_by_month = get_books_read_by_month(user.username)
# Initialize the Axis for graphs, X-Axis is months, Y-axis is books read
months = [i+1 for i in range(12)]
books_read = [0 for _ in range(12)]
# Set the value for books read per month on Y-Axis
for num_books_read in books_read_by_month:
list_index = num_books_read['date_created__month'] - 1
books_read[list_index] = num_books_read['book_count']
# Generate a scatter plot HTML
figure = graphs.Figure()
scatter = graphs.Scatter(x=months, y=books_read)
figure.add_trace(scatter)
figure.update_layout(xaxis_title="Month", yaxis_title="No. of books read")
plot_html = plot(figure, output_type='div')
return render(request, 'profile.html',
{'user': user, 'permissions': permissions, 'books_read_plot': plot_html}
@login_required
def reading_history(request):
user = request.user.username
books_read = get_books_read(user)
# Create an object to create files in memory
temp_file = BytesIO()
# Start a new workbook
workbook = xlsxwriter.Workbook(temp_file)
worksheet = workbook.add_worksheet()
# Prepare the data to be written
data = []
for book_read in books_read:
data.append([book_read['title'], str(book_read['completed_on'])])
# Write data to worksheet
for row in range(len(data)):
for col in range(len(data[row])):
worksheet.write(row, col, data[row][col])
# Close the workbook
workbook.close()
# Capture data from memory file
data_to_download = temp_file.getvalue()
# Prepare response for download
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=reading_history.xlsx'
response.write(data_to_download)
return response
|
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
"""
try:
with open(filename, 'w') as csv_file:
csv_writer = csv.writer(csv_file)
csv_writer.writerow(header)
csv_writer.writerows(data)
except (IOError, OSError) as csv_file_error:
print("Unable to write the contents to csv file. Exception: {}".format(csv_file_error))
if __name__ == '__main__':
header = ['name', 'age', 'gender']
data = [['Richard', 32, 'M'], ['Mumzil', 21, 'F'], ['Melinda', 25, 'F']]
filename = 'sample_output.csv'
write_csv(filename, header, data)
|
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, 'permissions': permissions})
|
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.FILES["file_upload"].chunks():
output_file.write(chunk)
return render(request, "media-example.html")
|
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 import Book, Publisher
from reviews.views import book_media
class Activity1Test(TestCase):
@classmethod
def setUpTestData(cls):
p = Publisher.objects.create(name='Test Publisher')
b = Book.objects.create(title='Test Book', publication_date=timezone.now(), publisher=p)
def test_form_definition(self):
"""Test that the BookMediaForm has the correct field."""
f = BookMediaForm()
self.assertEquals(f.Meta.model, Book)
self.assertEquals(f.Meta.fields, ['cover', 'sample'])
self.assertIsInstance(f.fields['cover'], forms.ImageField)
self.assertIsInstance(f.fields['sample'], forms.FileField)
def test_form_in_template(self):
"""Test that the form is in the rendered template."""
c = Client()
resp = c.get('/books/1/media/')
self.assertEquals(resp.status_code, 200)
self.assertIn(b'<label for="id_sample">Sample:</label>', resp.content)
self.assertIn(b'<label for="id_cover">Cover:</label>', resp.content)
self.assertIn(b'<input type="file" name="cover" accept="image/*" id="id_cover">',
resp.content)
self.assertIn(b'<input type="file" name="sample" id="id_sample">',
resp.content)
@mock.patch('reviews.views.render', name='render')
@mock.patch('reviews.views.get_object_or_404', name='get_object_or_404')
def test_render_call(self, mock_g_o_o_404 ,mock_render):
"""Test that the view calls render with the correct arguments and returns it."""
request = mock.MagicMock(name='request')
resp = book_media(request, 'pk')
mock_g_o_o_404.assert_called_with(Book, pk='pk')
self.assertEquals(resp, mock_render.return_value)
self.assertEquals(mock_render.call_args[0][0], request)
self.assertEquals(mock_render.call_args[0][1], 'reviews/instance-form.html')
self.assertIsInstance(mock_render.call_args[0][2], dict)
self.assertEquals(len(mock_render.call_args[0][2]), 4)
self.assertIsInstance(mock_render.call_args[0][2]['form'], BookMediaForm)
self.assertEquals(mock_render.call_args[0][2]['instance'], mock_g_o_o_404.return_value)
self.assertEquals(mock_render.call_args[0][2]['model_type'], 'Book')
self.assertEquals(mock_render.call_args[0][2]['is_file_upload'], True)
def test_book_media_upload(self):
"""
Test the upload functionality to the book_media view. Check it exists on disk and the image has been resized.
"""
cover_filename = 'machine-learning-for-algorithmic-trading.png'
cover_save_path = os.path.join(settings.MEDIA_ROOT, 'book_covers', cover_filename)
sample_filename = 'machine-learning-for-trading.pdf'
sample_save_path = os.path.join(settings.MEDIA_ROOT, 'book_samples', sample_filename)
try:
c = Client()
with open(os.path.join(settings.BASE_DIR, 'fixtures', cover_filename), 'rb') as cover_fp:
with open(os.path.join(settings.BASE_DIR, 'fixtures', sample_filename), 'rb') as sample_fp:
resp = c.post('/books/1/media/', {'cover': cover_fp, 'sample': sample_fp})
self.assertEquals(resp.status_code, 302)
self.assertEquals(resp['Location'], '/books/1/')
with open(cover_save_path, 'rb') as cover_image_fp:
cover = Image.open(cover_image_fp)
self.assertTrue(cover.width == 300 or cover.height == 300)
finally:
if os.path.exists(cover_save_path):
os.unlink(cover_save_path)
if os.path.exists(sample_save_path):
os.unlink(sample_save_path)
|
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.publisher.name
get_publisher.short_description = _("Publisher")
class BookrAdmin(admin.AdminSite):
site_header = "Bookr Administration Portal"
site_title = "Bookr Administration Portal"
index_title = "Bookr Administration"
admin.site.register(Book, BooksAdmin)
|
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.assertIn('crispy_forms', settings.INSTALLED_APPS)
self.assertEquals(settings.CRISPY_TEMPLATE_PACK, 'bootstrap4')
def test_crispy_form_used_in_template(self):
"""Test that the {% crispy %} template tag is being used to render the form in search-results.html"""
with open(os.path.join(settings.BASE_DIR, 'reviews/templates/reviews/search-results.html')) as tf:
template_content = tf.read()
self.assertIn('{% load crispy_forms_tags %', template_content)
self.assertIn('{% crispy form %}', template_content)
self.assertNotIn('<form', template_content)
self.assertNotIn('</form>', template_content)
def test_rendered_form(self):
"""Test the rendered form view."""
c = Client()
resp = c.get('/book-search/')
self.assertIn(b'<form', resp.content)
self.assertIn(
b'<input type="text" name="search" minlength="3" class="textinput textInput form-control" id="id_search">',
resp.content)
self.assertIn(b'<select name="search_in" class="select form-control" id="id_search_in">', resp.content)
|
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(
model_name='book',
name='publisher',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='reviews.Publisher'),
),
migrations.AlterField(
model_name='review',
name='date_edited',
field=models.DateTimeField(help_text='The date and time the review was last edited.', null=True),
),
]
|
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."""
c = Client()
resp = c.get('/')
self.assertIn(b'<div class="container-fluid">', resp.content)
def test_fields_in_view(self):
""""
Test that fields exist in the rendered template.
"""
c = Client()
response = c.get('/publishers/new/')
self.assertIsNotNone(re.search(r'<input type="hidden" name="csrfmiddlewaretoken" value="\w+">',
response.content.decode('utf8')))
self.assertIn(
b'<label for="id_name">Name:</label> <input type="text" name="name" maxlength="50" required id="id_name"> '
b'<span class="helptext">The name of the Publisher.</span></p>',
response.content)
self.assertIn(
b'<label for="id_website">Website:</label> <input type="url" name="website" maxlength="200" '
b'required id="id_website"> <span class="helptext">The Publisher\'s website.</span></p>',
response.content)
self.assertIn(
b'<label for="id_email">Email:</label> <input type="email" name="email" maxlength="254" '
b'required id="id_email"> <span class="helptext">The Publisher\'s email address.</span>',
response.content)
self.assertIn(b'<button type="submit" class="btn btn-primary">\n Create\n </button>',
response.content)
def test_publisher_create(self):
"""Test the creation of a new Publisher"""
self.assertEqual(Publisher.objects.all().count(), 0)
c = Client()
publisher_name = '<NAME>'
publisher_website = 'http://www.example.com/test-publisher/'
publisher_email = '<EMAIL>'
response = c.post('/publishers/new/', {
'name': publisher_name,
'website': publisher_website,
'email': publisher_email
})
self.assertEqual(response.status_code, 302)
self.assertEqual(Publisher.objects.all().count(), 1)
publisher = Publisher.objects.first()
self.assertEqual(publisher.name, publisher_name)
self.assertEqual(publisher.website, publisher_website)
self.assertEqual(publisher.email, publisher_email)
self.assertEqual(response['Location'], '/publishers/{}/'.format(publisher.pk))
# the messages will be on the redirected to page
response = c.get(response['location'])
condensed_content = re.sub(r'\s+', ' ', response.content.decode('utf8').replace('\n', ''))
self.assertIn(
'<div class="alert alert-success" role="alert"> Publisher "Test Create Publisher" was created. '
'</div>', condensed_content)
def test_publisher_no_create(self):
"""Test that no Publisher is created if the form is invalid."""
self.assertEqual(Publisher.objects.all().count(), 0)
c = Client()
response = c.post('/publishers/new/', {
'name': '',
'website': 'not a url',
'email': 'not an email'
})
self.assertEqual(response.status_code, 200)
self.assertEqual(Publisher.objects.all().count(), 0)
def test_publisher_edit(self):
"""
Test editing a publisher, the initial GET should have a form with values and then the post should update the
Publisher rather than creating a new one.
"""
publisher_name = 'Test Edit Publisher'
publisher_website = 'http://www.example.com/edit-publisher/'
publisher_email = '<EMAIL>'
publisher = Publisher(name=publisher_name, website=publisher_website, email=publisher_email)
publisher.save()
self.assertEqual(Publisher.objects.all().count(), 1)
c = Client()
response = c.get('/publishers/{}/'.format(publisher.pk))
self.assertIn(b'value="Test Edit Publisher"', response.content)
self.assertIn(b'value="http://www.example.com/edit-publisher/"', response.content)
self.assertIn(b'value="<EMAIL>"', response.content)
self.assertIn(b'<button type="submit" class="btn btn-primary">\n Save\n </button>',
response.content)
response = c.post('/publishers/{}/'.format(publisher.pk), {
'name': '<NAME>',
'website': 'https://www.example.com/updated/',
'email': '<EMAIL>'
})
self.assertEqual(response.status_code, 302)
self.assertEqual(Publisher.objects.all().count(), 1)
publisher2 = Publisher.objects.first()
self.assertEqual(publisher2.pk, publisher.pk)
self.assertEqual(publisher2.name, '<NAME>')
self.assertEqual(publisher2.website, 'https://www.example.com/updated/')
self.assertEqual(publisher2.email, '<EMAIL>')
# the messages will be on the redirected to page
response = c.get(response['location'])
condensed_content = re.sub(r'\s+', ' ', response.content.decode('utf8').replace('\n', ''))
self.assertIn(
'<div class="alert alert-success" role="alert"> Publisher "Updated Name" was updated. </div>',
condensed_content)
def test_404_response(self):
"""When getting a Publisher that doesn't exist we should get a 404 response."""
c = Client()
response = c.get('/publishers/123/')
self.assertEquals(response.status_code, 404)
|
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.filter(first_names='Rowel')
Contributor.objects.filter(first_names='Nobody')
|
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.ModelSerializer):
class Meta:
model = Publisher
fields = ['name', 'website', 'email']
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['username', 'email']
class ReviewSerializer(serializers.ModelSerializer):
creator = UserSerializer(read_only=True)
book = serializers.StringRelatedField(read_only=True)
class Meta:
model = Review
fields = ['pk', 'content', 'date_created', 'date_edited', 'rating', 'creator', 'book', 'book_id']
def create(self, validated_data):
request = self.context["request"]
creator = request.user
if not creator.is_authenticated:
raise NotAuthenticated('Authentication required.')
book = Book.objects.get(pk=request.data['book_id'])
return Review.objects.create(content=validated_data['content'], book=book, creator=creator,
rating=validated_data['rating'])
def update(self, instance, validated_data):
request = self.context['request']
creator = request.user
if not creator.is_authenticated or instance.creator_id != creator.pk:
raise PermissionDenied('Permission denied, you are not the creator of this review')
instance.content = validated_data['content']
instance.rating = validated_data['rating']
instance.date_edited = timezone.now()
instance.save()
return instance
class BookSerializer(serializers.ModelSerializer):
publisher = PublisherSerializer()
rating = serializers.SerializerMethodField('book_rating')
reviews = serializers.SerializerMethodField('book_reviews')
def book_rating(self, book):
reviews = book.review_set.all()
if reviews:
return average_rating([review.rating for review in reviews])
else:
None
def book_reviews(self, book):
reviews = book.review_set.all()
if reviews:
return ReviewSerializer(reviews, many=True).data
else:
None
class Meta:
model = Book
fields = ['title', 'publication_date', 'isbn', 'publisher', 'rating', 'reviews'] |
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"),
("contributor", "Contributor")
))
class PublisherForm(forms.ModelForm):
class Meta:
model = Publisher
fields = "__all__"
class ReviewForm(forms.ModelForm):
class Meta:
model = Review
exclude = ["date_edited", "book"]
rating = forms.IntegerField(min_value=0, max_value=5)
|
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
self.assertEqual(settings.MEDIA_URL, '/media/')
with open(os.path.join(media_root, 'test.txt'), 'rb') as f:
hw_content = f.read()
resp = urlopen(self.live_server_url + '/media/test.txt')
self.assertEquals(hw_content, resp.read())
|
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, 'static', 'react-example.js')))
self.assertFalse(os.path.exists(os.path.join(settings.BASE_DIR, 'templates', 'react-example.html')))
with self.assertRaises(ImportError):
from reviews.views import react_example
c = Client()
resp = c.get('/react-example/')
self.assertEquals(resp.status_code, 404)
def test_template_content(self):
"""Test that the scripts and container have been added to the template."""
c = Client()
resp = c.get('/')
self.assertIn(b'<div id="recent_reviews"></div>', resp.content)
self.assertIn(b'<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>',
resp.content)
self.assertIn(
b'<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>',
resp.content)
self.assertIn(b'<script crossorigin src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>', resp.content)
self.assertIn(b'<script src="/static/recent-reviews.js" type="text/babel"></script>', resp.content)
self.assertIn(b'ReactDOM.render(<RecentReviews url="/api/reviews/?limit=6" />,', resp.content)
self.assertIn(b'document.getElementById(\'recent_reviews\')', resp.content)
def test_scripts_inside_content_block(self):
"""The script and recent_reviews div should not be in pages other than /"""
c = Client()
resp = c.get('/books/')
self.assertNotIn(b'<div id="recent_reviews"></div>', resp.content)
self.assertNotIn(b'<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>',
resp.content)
self.assertNotIn(
b'<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>',
resp.content)
self.assertNotIn(b'<script crossorigin src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>', resp.content)
self.assertNotIn(b'<script src="/static/recent-reviews.js" type="text/babel"></script>', resp.content)
self.assertNotIn(b'ReactDOM.render(<RecentReviews url="/api/reviews/?limit=6" />,', resp.content)
self.assertNotIn(b'document.getElementById(\'recent_reviews\')', resp.content)
def test_js_content(self):
"""Test that some expected things are in the JS file."""
with open(os.path.join(settings.BASE_DIR, 'static', 'recent-reviews.js')) as f:
static_content = f.read()
# remove leading/trailing whitespace to make comparison more robust
s = re.sub(r'^\s+', '', static_content, flags=re.MULTILINE)
s = re.sub(r'\s+$', '', s, flags=re.MULTILINE)
review_display_class = """class ReviewDisplay extends React.Component {
constructor(props) {
super(props);
this.state = { review: props.review };
}
render () {
const review = this.state.review;
return <div className="col mb-4">
<div className="card">
<div className="card-body">
<h5 className="card-title">{ review.book }
<strong>({ review.rating })</strong>
</h5>
<h6 className="card-subtitle mb-2 text-muted">{ review.creator.email }</h6>
<p className="card-text">{ review.content }</p>
</div>
<div className="card-footer">
<a href={'/books/' + review.book_id + '/' } className="card-link">View Book</a>
</div>
</div>
</div>;
}
}"""
self.assertIn(review_display_class, s)
recent_reviews_class = """class RecentReviews extends React.Component {
constructor(props) {
super(props);
this.state = {
reviews: [],
currentUrl: props.url,
nextUrl: null,
previousUrl: null,
loading: false
};
}
fetchReviews() {
if (this.state.loading)
return;
this.setState( {loading: true} );
fetch(this.state.currentUrl, {
method: 'GET',
headers: {
Accept: 'application/json'
}
}).then((response) => {
return response.json()
}).then((data) => {
this.setState({
loading: false,
reviews: data.results,
nextUrl: data.next,
previousUrl: data.previous
})
})
}
componentDidMount() {
this.fetchReviews()
}
loadNext() {
if (this.state.nextUrl == null)
return;
this.state.currentUrl = this.state.nextUrl;
this.fetchReviews();
}
loadPrevious() {
if (this.state.previousUrl == null)
return;
this.state.currentUrl = this.state.previousUrl;
this.fetchReviews();
}
render() {
if (this.state.loading) {
return <h5>Loading...</h5>;
}
const previousButton = <button
className="btn btn-secondary"
onClick={ () => { this.loadPrevious() } }
disabled={ this.state.previousUrl == null }>
Previous
</button>;
const nextButton = <button
className="btn btn-secondary float-right"
onClick={ () => { this.loadNext() } }
disabled={ this.state.nextUrl == null }>
Next
</button>;
let reviewItems;
if (this.state.reviews.length === 0) {
reviewItems = <h5>No reviews to display.</h5>
} else {
reviewItems = this.state.reviews.map((review) => {
return <ReviewDisplay key={review.pk} review={review}/>
})
}
return <div>
<div className="row row-cols-1 row-cols-sm-2 row-cols-md-3">
{ reviewItems }
</div>
<div>
{ previousButton }
{ nextButton }
</div>
</div>;
}
}"""
self.assertIn(recent_reviews_class, s)
|
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', website='www.packt.com', email='<EMAIL>')
def test_create_publisher(self):
self.assertIsInstance(self.p, Publisher)
def test_str_representation(self):
self.assertEquals(str(self.p), "Packt")
class TestGreetingView(TestCase):
"""Test the greeting view."""
def setUp(self):
self.client = Client()
def test_greeting_view(self):
response = self.client.get('/test/greeting')
self.assertEquals(response.status_code, 200)
class TestLoggedInGreetingView(TestCase):
"""Test the greeting view for the authenticated users."""
def setUp(self):
test_user = User.objects.create_user(username='testuser', password='<PASSWORD>')
test_user.save()
self.client = Client()
def test_user_greeting_not_authenticated(self):
response = self.client.get('/test/greet_user')
self.assertEquals(response.status_code, 302)
def test_user_authenticated(self):
login = self.client.login(username='testuser', password='<PASSWORD>')
response = self.client.get('/test/greet_user')
self.assertEquals(response.status_code, 200)
|
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 media_example
class Exercise6Test(LiveServerTestCase):
def test_form_definition(self):
"""Test that the UploadForm has the correct field."""
f = UploadForm()
self.assertIsInstance(f.fields['image_upload'], forms.ImageField)
self.assertIsInstance(f.fields['file_upload'], forms.FileField)
def test_form_in_template(self):
"""Test that the form is in the rendered template."""
c = Client()
resp = c.get('/media-example/')
self.assertEquals(resp.status_code, 200)
self.assertIn(b'<label for="id_file_upload">File upload:</label>', resp.content)
self.assertIn(b'<label for="id_image_upload">Image upload:</label>', resp.content)
self.assertIn(b'<input type="file" name="image_upload" accept="image/*" required id="id_image_upload">',
resp.content)
self.assertIn(b'<input type="file" name="file_upload" required id="id_file_upload">',
resp.content)
@mock.patch('media_example.views.render', name='render')
def test_render_call(self, mock_render):
"""Test that the view calls render with the correct arguments and returns it."""
request = mock.MagicMock(name='request')
resp = media_example(request)
self.assertEquals(resp, mock_render.return_value)
self.assertEquals(mock_render.call_args[0][0], request)
self.assertEquals(mock_render.call_args[0][1], 'media-example.html')
self.assertIsInstance(mock_render.call_args[0][2], dict)
self.assertEquals(len(mock_render.call_args[0][2]), 2)
self.assertIsInstance(mock_render.call_args[0][2]['form'], UploadForm)
self.assertIsNone(mock_render.call_args[0][2]['instance'], UploadForm)
def test_media_example_upload(self):
"""
Test the upload functionality to the media_example view. Check it can be downloaded again.
"""
logo_filename = 'cover.jpg'
logo_save_path = os.path.join(settings.MEDIA_ROOT, 'images', logo_filename)
css_filename = 'sample.txt'
css_save_path = os.path.join(settings.MEDIA_ROOT, 'files', css_filename)
try:
c = Client()
with open(os.path.join(settings.BASE_DIR, 'fixtures', logo_filename), 'rb') as logo_fp:
with open(os.path.join(settings.BASE_DIR, 'fixtures', css_filename), 'rb') as css_fp:
resp = c.post('/media-example/', {'file_upload': css_fp, 'image_upload': logo_fp})
self.assertEquals(resp.status_code, 200)
self.assertIn(b'<img src="/media/images/cover.jpg">', resp.content)
with open(logo_save_path, 'rb') as uploaded_logo_fp:
media_file = urlopen(self.live_server_url + '/media/images/' + logo_filename)
self.assertEquals(media_file.read(), uploaded_logo_fp.read())
with open(css_save_path, 'rb') as uploaded_css_fp:
media_file = urlopen(self.live_server_url + '/media/files/' + css_filename)
self.assertEquals(media_file.read(), uploaded_css_fp.read())
finally:
if os.path.exists(logo_save_path):
os.unlink(logo_save_path)
if os.path.exists(css_save_path):
os.unlink(css_save_path)
|
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_framework.response import Response
from rest_framework.status import HTTP_404_NOT_FOUND, HTTP_200_OK
from rest_framework.views import APIView
from .models import Book, Review
from .serializers import BookSerializer, ReviewSerializer
class Login(APIView):
def post(self, request):
user = authenticate(username=request.data.get("username"), password=request.data.get("password"))
if not user:
return Response({'error': 'Credentials are incorrect or user does not exist'}, status=HTTP_404_NOT_FOUND)
token, _ = Token.objects.get_or_create(user=user)
return Response({'token': token.key}, status=HTTP_200_OK)
class BookViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
authentication_classes = []
permission_classes = []
class ReviewViewSet(viewsets.ModelViewSet):
queryset = Review.objects.order_by('-date_created')
serializer_class = ReviewSerializer
pagination_class = LimitOffsetPagination
authentication_classes = []
|
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_date = serializers.DateField()
isbn = serializers.CharField()
publisher = PublisherSerializer()
|
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_VAR:' + os.environ.get('SET_VAR', ''))
# All these values were provided from the shell in some way
print('HOME:' + os.environ.get('HOME', ''))
print('VAR1:' + os.environ.get('VAR1', ''))
print('VAR2:' + os.environ.get('VAR2', ''))
print('VAR3:' + os.environ.get('VAR3', ''))
print('VAR4:' + os.environ.get('VAR4', ''))
|
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 least lets us know Django is
installed properly.
"""
c = Client()
response = c.get('/admin/')
self.assertEqual(response.status_code, 302) # redirect to login page
|
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)
return TemplateResponse(request, "admin/admin_profile.html", context)
def get_urls(self):
urls = super().get_urls()
url_patterns = [
path("admin_profile", self.admin_view(self.profile_view))
]
return urls + url_patterns
|
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_text="The Publisher's email address.")
def __str__(self):
return self.name
|
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_required
def profile(request):
user = request.user
permissions = user.get_all_permissions()
# Get the books read in different months this year
books_read_by_month = get_books_read_by_month(user.username)
# Initialize the Axis for graphs, X-Axis is months, Y-axis is books read
months = [i+1 for i in range(12)]
books_read = [0 for _ in range(12)]
# Set the value for books read per month on Y-Axis
for num_books_read in books_read_by_month:
list_index = num_books_read['date_created__month'] - 1
books_read[list_index] = num_books_read['book_count']
# Generate a scatter plot HTML
figure = graphs.Figure()
scatter = graphs.Scatter(x=months, y=books_read)
figure.add_trace(scatter)
figure.update_layout(xaxis_title="Month", yaxis_title="No. of books read")
plot_html = plot(figure, output_type='div')
return render(request, 'profile.html',
{'user': user, 'permissions': permissions, 'books_read_plot': plot_html}
|
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 = Publisher
fields = ['name', 'website', 'email']
class BookSerializer(serializers.ModelSerializer):
publisher = PublisherSerializer()
class Meta:
model = Book
fields = ['title', 'publication_date', 'isbn', 'publisher']
class ContributionSerializer(serializers.ModelSerializer):
book = BookSerializer()
class Meta:
model = BookContributor
fields = ['book', 'role']
class ContributorSerializer(serializers.ModelSerializer):
bookcontributor_set = ContributionSerializer(read_only=True, many=True)
number_contributions = serializers.ReadOnlyField()
class Meta:
model = Contributor
fields = ['first_names', 'last_names', 'email', 'bookcontributor_set', 'number_contributions']
|
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('/')
self.assertIn(b'Hello from a template!', response.content)
|
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 worksheet
def write_data(worksheet, data):
"""Write data to the worksheet."""
for row in range(len(data)):
for col in range(len(data[row])):
worksheet.write(row, col, data[row][col])
def close_workbook(workbook):
"""Close an opened workbook."""
workbook.close()
if __name__ == '__main__':
data = [['<NAME>', 38], ['<NAME>', 22], ['<NAME>', 28], ['<NAME>', 42]]
workbook = create_workbook('sample_workbook.xlsx')
worksheet = create_worksheet(workbook)
write_data(worksheet, data)
close_workbook(workbook)
|
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):
"""
These tests use `StaticLiveServerTestCase` and `urlopen` since the normal `TestCase` uses a special server that does
not serve static assets.
"""
def test_django_conf(self):
"""
Check that `reviews` is in `settings.INSTALLED_APPS` and that the static dir is set to <projectdir>/static.
STATIC_ROOT and STATICFILES_STORAGE should not be set.
"""
self.assertIn('reviews', settings.INSTALLED_APPS)
self.assertEquals([settings.BASE_DIR + '/static'], settings.STATICFILES_DIRS)
self.assertIsNone(settings.STATIC_ROOT)
self.assertEquals(settings.STATICFILES_STORAGE, 'django.contrib.staticfiles.storage.StaticFilesStorage')
def test_reviews_logo_get(self):
"""
Test that the reviews logo.png can be downloaded, and the content matches that on disk. This also checks the
logo.png is in the right location and is being served using the static files finder.
"""
response = urlopen(self.live_server_url + '/static/reviews/logo.png').read()
current_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(current_dir, 'static', 'reviews', 'logo.png'), 'rb') as f:
self.assertEqual(response, f.read())
def test_main_logo_get(self):
"""
Test that the main logo.png can be downloaded, and the content matches that on disk. This also checks the
logo.png is in the right location and is being served using the static files finder.
"""
response = urlopen(self.live_server_url + '/static/logo.png').read()
with open(os.path.join(settings.BASE_DIR, 'static', 'logo.png'), 'rb') as f:
self.assertEqual(response, f.read())
def test_main_css_get(self):
"""
Test that the main.css can be downloaded, and the content matches that on disk. This also checks that main.css
is in the right location and is being served using the static files finder.
Since we have the contents of the file we can check it has the right rules too.
"""
response = urlopen(self.live_server_url + '/static/main.css').read()
with open(os.path.join(settings.BASE_DIR, 'static', 'main.css'), 'rb') as f:
self.assertEqual(response, f.read())
self.assertIn(b'.navbar', response)
self.assertIn(b'.navbar-brand', response)
self.assertIn(b'.navbar-brand > img', response)
self.assertIn(b'body', response)
self.assertIn(b'h1, h2, h3, h4, h5, h6', response)
def test_base_html_content(self):
"""
In the base HTML we should see: {% load static %}, CSS loaded with {% static %} template tag, fonts load CSS
tag, main logo in brand block and no <style>...</style> tags.
"""
base_template = read_content(os.path.join(settings.BASE_DIR, 'templates', 'base.html'))
self.assertIn('{% load static %}', base_template)
self.assertIn('<link rel="stylesheet" href="{% static \'main.css\' %}">', base_template)
self.assertIn('<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Libre+Baskerville|'
'Source+Sans+Pro&display=swap">', base_template)
self.assertIn(
'<a class="navbar-brand" href="/">{% block brand %}<img src="{% static \'logo.png\' %}">{% endblock %}</a>',
base_template)
self.assertNotIn('<style>', base_template)
self.assertNotIn('</style>', base_template)
def test_base_logo_display(self):
"""Test that the base template has no logo."""
c = Client()
resp = c.get('/')
self.assertIn(b'<a class="navbar-brand" href="/"><img src="/static/logo.png"></a>', resp.content)
def test_reviews_logo_display(self):
"""Test that the reviews page(s) have a logo set."""
c = Client()
resp = c.get('/books/')
self.assertIn(b'<a class="navbar-brand" href="/"><img src="/static/reviews/logo.png"></a>', resp.content)
def test_review_base_extends_main(self):
"""Test that the reviews base.html extends from the main base.html"""
reviews_base = read_content(os.path.join(settings.BASE_DIR, 'reviews', 'templates', 'reviews', 'base.html'))
self.assertTrue(reviews_base.startswith('{% extends \'base.html\' %}'))
def test_reviews_templates_extend_reviews_base(self):
"""Test that the reviews templates extends the reviews base.html file."""
book_detail_template = read_content(os.path.join(settings.BASE_DIR, 'reviews', 'templates', 'reviews',
'book_detail.html'))
self.assertTrue(book_detail_template.startswith('{% extends \'reviews/base.html\' %}'))
book_list_template = read_content(os.path.join(settings.BASE_DIR, 'reviews', 'templates', 'reviews',
'book_list.html'))
self.assertTrue(book_list_template.startswith('{% extends \'reviews/base.html\' %}'))
|
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
class Exercise7Test(LiveServerTestCase):
def test_form_definition(self):
"""Test that the UploadForm has the correct field."""
f = UploadForm()
self.assertEquals(f.Meta.model, ExampleModel)
self.assertEquals(f.Meta.fields, '__all__')
self.assertIsInstance(f.fields['image_field'], forms.ImageField)
self.assertIsInstance(f.fields['file_field'], forms.FileField)
def test_form_in_template(self):
"""Test that the form is in the rendered template."""
c = Client()
resp = c.get('/media-example/')
self.assertEquals(resp.status_code, 200)
self.assertIn(b'<label for="id_file_field">File field:</label>', resp.content)
self.assertIn(b'<label for="id_image_field">Image field:</label>', resp.content)
self.assertIn(b'<input type="file" name="image_field" accept="image/*" required id="id_image_field">',
resp.content)
self.assertIn(b'<input type="file" name="file_field" required id="id_file_field">',
resp.content)
@mock.patch('media_example.views.render', name='render')
def test_render_call(self, mock_render):
"""Test that the view calls render with the correct arguments and returns it."""
request = mock.MagicMock(name='request')
resp = media_example(request)
self.assertEquals(resp, mock_render.return_value)
self.assertEquals(mock_render.call_args[0][0], request)
self.assertEquals(mock_render.call_args[0][1], 'media-example.html')
self.assertIsInstance(mock_render.call_args[0][2], dict)
self.assertEquals(len(mock_render.call_args[0][2]), 2)
self.assertIsInstance(mock_render.call_args[0][2]['form'], UploadForm)
self.assertIsNone(mock_render.call_args[0][2]['instance'], UploadForm)
def test_media_example_upload(self):
"""
Test the upload functionality to the media_example view. Check it can be downloaded again.
"""
logo_filename = 'cover.jpg'
logo_save_path = os.path.join(settings.MEDIA_ROOT, 'images', logo_filename)
css_filename = 'sample.txt'
css_save_path = os.path.join(settings.MEDIA_ROOT, 'files', css_filename)
try:
c = Client()
with open(os.path.join(settings.BASE_DIR, 'fixtures', logo_filename), 'rb') as logo_fp:
with open(os.path.join(settings.BASE_DIR, 'fixtures', css_filename), 'rb') as css_fp:
resp = c.post('/media-example/', {'file_field': css_fp, 'image_field': logo_fp})
self.assertEquals(resp.status_code, 200)
self.assertIn(b'<img src="/media/images/cover.jpg">', resp.content)
with open(logo_save_path, 'rb') as uploaded_logo_fp:
media_file = urlopen(self.live_server_url + '/media/images/' + logo_filename)
self.assertEquals(media_file.read(), uploaded_logo_fp.read())
with open(css_save_path, 'rb') as uploaded_css_fp:
media_file = urlopen(self.live_server_url + '/media/files/' + css_filename)
self.assertEquals(media_file.read(), uploaded_css_fp.read())
finally:
if os.path.exists(logo_save_path):
os.unlink(logo_save_path)
if os.path.exists(css_save_path):
os.unlink(css_save_path)
|
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.")
@login_required
def greeting_view_user(request):
"""Greeting view for the user."""
user = request.user
return HttpResponse("Welcome to Bookr! {username}".format(username=user))
|
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)
figure.add_trace(scatter)
return plot(figure, output_type='div')
def generate_html(plot_html):
"""Generate an HTML page for the provided plot."""
html_content = "<html><head><title>Plot Demo</title></head><body>{}</body></html>".format(plot_html)
try:
with open('plot_demo.html', 'w') as plot_file:
plot_file.write(html_content)
except (IOError, OSError) as file_io_error:
print("Unable to generate plot file. Exception: {}".format(file_io_error))
if __name__ == '__main__':
x = [1,2,3,4,5]
y = [3,8,7,9,2]
plot_html = generate_scatter_plot(x, y)
generate_html(plot_html)
|
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 the HTML from the view, including newly-added CSRF token."""
c = Client()
response = c.get('/form-example/')
self.assertIsNotNone(re.search(r'<input type="hidden" name="csrfmiddlewaretoken" value="\w+">',
response.content.decode('ascii')))
self.assertIn(b'<label for="id_text_input">Text Input</label><br>', response.content)
self.assertIn(
b'<input id="id_text_input" type="text" name="text_input" value="" placeholder="Enter some text">',
response.content)
self.assertIn(b'<label for="id_password_input">Password Input</label><br>', response.content)
self.assertIn(
b'<input id="id_password_input" type="password" name="password_input" value="" '
b'placeholder="Your password">', response.content)
self.assertIn(
b'<input id="id_checkbox_input" type="checkbox" name="checkbox_on" value="Checkbox Checked" checked>',
response.content)
self.assertIn(b'<label for="id_checkbox_input">Checkbox</label>', response.content)
self.assertIn(b'<input id="id_radio_one_input" type="radio" name="radio_input" value="Value One">',
response.content)
self.assertIn(b'<label for="id_radio_one_input">Value One</label>', response.content)
self.assertIn(b'<input id="id_radio_two_input" type="radio" name="radio_input" value="Value Two" checked>',
response.content)
self.assertIn(b'<label for="id_radio_two_input">Value Two</label>', response.content)
self.assertIn(b'<input id="id_radio_three_input" type="radio" name="radio_input" value="Value Three">',
response.content)
self.assertIn(b'<label for="id_radio_three_input">Value Three</label>', response.content)
self.assertIn(b'<label for="id_favorite_book">Favorite Book</label><br>', response.content)
self.assertIn(b'<select id="id_favorite_book" name="favorite_book">', response.content)
self.assertIn(b'<optgroup label="Non-Fiction">', response.content)
self.assertIn(b'<option value="1">Deep Learning with Keras</option>', response.content)
self.assertIn(b'<option value="2">Web Development with Django</option>', response.content)
self.assertIn(b'<optgroup label="Fiction">', response.content)
self.assertIn(b'<option value="3">Brave New World</option>', response.content)
self.assertIn(b'<option value="4">The Great Gatsby</option>', response.content)
self.assertIn(b'<label for="id_books_you_own">Books You Own</label><br>', response.content)
self.assertIn(b'<select id="id_books_you_own" name="books_you_own" multiple>', response.content)
self.assertIn(b'<optgroup label="Non-Fiction">', response.content)
self.assertIn(b'<option value="1">Deep Learning with Keras</option>', response.content)
self.assertIn(b'<option value="2">Web Development with Django</option>', response.content)
self.assertIn(b'<optgroup label="Fiction">', response.content)
self.assertIn(b'<option value="3">Brave New World</option>', response.content)
self.assertIn(b'<option value="4">The Great Gatsby</option>', response.content)
self.assertIn(b'<label for="id_text_area">Text Area</label><br>', response.content)
self.assertIn(
b'<textarea name="text_area" id="id_text_area" placeholder="Enter multiple lines of text"></textarea>',
response.content)
self.assertIn(b'<label for="id_number_input">Number Input</label><br>', response.content)
self.assertIn(
b'<input id="id_number_input" type="number" name="number_input" value="" step="any" '
b'placeholder="A number">', response.content)
self.assertIn(b'<label for="id_email_input">Email Input</label><br>', response.content)
self.assertIn(
b'<input id="id_email_input" type="email" name="email_input" value="" placeholder="Your email address">',
response.content)
self.assertIn(b'<label for="id_date_input">Date Input</label><br>', response.content)
self.assertIn(b'<input id="id_date_input" type="date" name="date_input" value="2019-11-23">', response.content)
self.assertIn(b'<input type="submit" name="submit_input" value="Submit Input">', response.content)
self.assertIn(b'<button type="submit" name="button_element" value="Button Element">', response.content)
self.assertIn(b'Button With <strong>Styled</strong> Text', response.content)
self.assertIn(b'</button>', response.content)
self.assertIn(b'<input type="hidden" name="hidden_input" value="Hidden Value">', response.content)
def test_method_in_view(self):
"""Test that the method is included in the HTML output"""
c = Client()
response = c.get('/form-example/')
self.assertIn(b'<h4>Method: GET</h4>', response.content)
response = c.post('/form-example/')
self.assertIn(b'<h4>Method: POST</h4>', response.content)
@mock.patch('form_example.views.print')
def test_get_debug_output(self, mock_print):
"""Mock the print() function to test the debug output with GET request (no output)."""
mock_request = mock.MagicMock(spec=HttpRequest)
mock_request.method = 'GET'
mock_request.POST = QueryDict()
mock_request.META = {}
form_example(mock_request)
mock_print.assert_not_called()
@mock.patch('form_example.views.print')
def test_post_debug_output(self, mock_print):
"""Mock the print() function to test the debug output with posted data."""
mock_request = mock.MagicMock(spec=HttpRequest)
mock_request.method = 'POST'
mock_request.POST = QueryDict(b'csrfmiddlewaretoken='
b'<KEY>&'
b'text_input=Text&password_input=Password&checkbox_on=Checkbox+Checked&'
b'radio_input=Value+Two&favorite_book=1&books_you_own=1&books_you_own=3&'
b'text_area=Text+box+text.&number_input=4.5&email_input=user%40example.com&'
b'date_input=2019-11-23&button_element=Button+Element&hidden_input=Hidden+Value')
mock_request.META = {}
form_example(mock_request)
mock_print.assert_any_call(
"csrfmiddlewaretoken: ['<KEY>']")
mock_print.assert_any_call("text_input: ['Text']")
mock_print.assert_any_call("password_input: ['Password']")
mock_print.assert_any_call("checkbox_on: ['Checkbox Checked']")
mock_print.assert_any_call("radio_input: ['Value Two']")
mock_print.assert_any_call("favorite_book: ['1']")
mock_print.assert_any_call("books_you_own: ['1', '3']")
mock_print.assert_any_call("text_area: ['Text box text.']")
mock_print.assert_any_call("number_input: ['4.5']")
mock_print.assert_any_call("email_input: ['<EMAIL>']")
mock_print.assert_any_call("date_input: ['2019-11-23']")
mock_print.assert_any_call("button_element: ['Button Element']")
mock_print.assert_any_call("hidden_input: ['Hidden Value']")
|
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(settings.BASE_DIR, 'reviews/templates/base.html')
self.assertTrue(os.path.exists(template_path))
with open(template_path) as tf:
contents = tf.read()
self.assertIn('Hello from a template!', contents)
|
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.DateTimeField(null=True, help_text="Project completion time")
def __str__(self):
return self.name
class Task(models.Model):
title = models.CharField(max_length=100,
help_text="Task title")
description = models.TextField(help_text="Task description")
project = models.ForeignKey(Project, on_delete=models.CASCADE)
time_estimate = models.IntegerField(help_text="Time in hours required to complete the task.")
completed = models.BooleanField(default=False, help_text="Task completion status")
def __str__(self):
return self.title |
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-server-test-kamatera.conf"):
os.unlink("/etc/salt/cloud.providers.d/cloudcli-server-test-kamatera.conf")
with open("/etc/salt/cloud.providers.d/cloudcli-server-test-kamatera.conf", "w") as f:
f.write("""
cloudcli-server-test-kamatera:
driver: kamatera
api_client_id: {KAMATERA_API_CLIENT_ID}
api_secret: {KAMATERA_API_SECRET}
api_url: {KAMATERA_API_URL}
""".format(**os.environ))
print("listing locations...")
with open(os.path.join(outputdir, "salt-locations.json"), "wb") as f:
f.write(subprocess.check_output(["%s/salt-cloud" % os.environ["SALT_BIN_DIR"], "--out=json", "--list-locations", "cloudcli-server-test-kamatera"]))
with open(os.path.join(outputdir, "salt-locations.json")) as f:
locations = json.load(f)["cloudcli-server-test-kamatera"]["kamatera"]
assert locations["IL"] == "<NAME>, Israel (Middle East)"
assert len(locations) > 10
print("OK")
print("listing sizes...")
with open(os.path.join(outputdir, "salt-sizes.json"), "wb") as f:
f.write(subprocess.check_output(["%s/salt-cloud" % os.environ["SALT_BIN_DIR"], "--out=json", "--location=IL", "--list-sizes", "cloudcli-server-test-kamatera"]))
with open(os.path.join(outputdir, "salt-sizes.json")) as f:
sizes = json.load(f)["cloudcli-server-test-kamatera"]["kamatera"]
assert len(sizes) > 3
assert sizes["B"]["name"] == "Type B - General Purpose"
print("OK")
print("listing available server options...")
with open(os.path.join(outputdir, "salt-server-options.json"), "wb") as f:
f.write(subprocess.check_output(["%s/salt-cloud" % os.environ["SALT_BIN_DIR"], "--out=json", "--location=IL", "-f", "avail_server_options", "cloudcli-server-test-kamatera"]))
with open(os.path.join(outputdir, "salt-server-options.json")) as f:
server_options = json.load(f)["cloudcli-server-test-kamatera"]["kamatera"]
assert len(server_options) > 1
assert server_options["monthlyTrafficPackage"]["t5000"] == "5000GB/month on 10Gbit/sec port"
print("OK")
print("listing images...")
with open(os.path.join(outputdir, "salt-images.json"), "wb") as f:
f.write(subprocess.check_output(["%s/salt-cloud" % os.environ["SALT_BIN_DIR"], "--out=json", "--location=IL", "--list-images", "cloudcli-server-test-kamatera"]))
with open(os.path.join(outputdir, "salt-images.json")) as f:
images = json.load(f)["cloudcli-server-test-kamatera"]["kamatera"]
assert len(images) > 10
assert images["IL:6000C29a5a7220dcf84716e7bba74215"] == "Ubuntu Server version 18.04 LTS (bionic) 64-bit"
print("OK")
CREATE_SERVER_NAME = os.environ.get("CREATE_SERVER_NAME")
if not CREATE_SERVER_NAME:
print("Skipping create server tests")
exit(0)
os.makedirs("/etc/salt/cloud.profiles.d", exist_ok=True)
if os.path.exists("/etc/salt/cloud.profiles.d/cloudcli-server-test.conf"):
os.unlink("/etc/salt/cloud.profiles.d/cloudcli-server-test.conf")
with open("/etc/salt/cloud.profiles.d/cloudcli-server-test.conf", "w") as f:
f.write("""
cloudcli-server-test:
size: my-size
provider: cloudcli-server-test-kamatera
location: IL
cpu_type: B
cpu_cores: 2
ram_mb: 2048
disk_size_gb: 20
extra_disk_sizes_gb:
- 15
billing_cycle: hourly
monthly_traffic_package: t5000
image: IL:6000C29a5a7220dcf84716e7bba74215
networks:
- name: wan
ip: auto
daily_backup: false
managed: false
""")
print("creating server...")
with open(os.path.join(outputdir, "salt-create-server.json"), "wb") as f:
f.write(subprocess.check_output(["%s/salt-cloud" % os.environ["SALT_BIN_DIR"], "--out=json", "-p", "cloudcli-server-test", CREATE_SERVER_NAME]))
with open(os.path.join(outputdir, "salt-create-server.json")) as f:
jsonlines = None
for line in f.readlines():
if line.strip() == "{":
jsonlines = ["{"]
elif jsonlines is not None:
jsonlines.append(line.strip())
created_server = json.loads("\n".join(jsonlines))[CREATE_SERVER_NAME]
assert created_server["deployed"] == True
created_server_name = created_server["name"]
print("created_server_name = " + created_server_name)
print("OK")
print("listing servers..")
with open(os.path.join(outputdir, "salt-query.json"), "wb") as f:
f.write(subprocess.check_output(["%s/salt-cloud" % os.environ["SALT_BIN_DIR"], "--out=json", "-Q"]))
with open(os.path.join(outputdir, "salt-query.json")) as f:
servers = json.load(f)["cloudcli-server-test-kamatera"]["kamatera"]
assert len(servers) > 0
assert servers[created_server_name]["state"] == "running"
print("OK")
print("deleting server...")
with open(os.path.join(outputdir, "salt-delete.json"), "wb") as f:
f.write(subprocess.check_output(["%s/salt-cloud" % os.environ["SALT_BIN_DIR"], "--out=json", "-y", "-d", created_server_name]))
with open(os.path.join(outputdir, "salt-delete.json")) as f:
servers = json.load(f)["cloudcli-server-test-kamatera"]["kamatera"]
assert len(servers) > 0
assert servers[created_server_name]["state"] == "destroyed"
assert servers[created_server_name]["success"] == True
print("OK")
|
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"],
description='SaltStack Cloud module for managing Kamatera compute resources',
long_description=long_description,
long_description_content_type="text/markdown",
author='Kamatera',
url='https://github.com/Kamatera/salt-cloud-module-kamatera',
license='MIT',
entry_points={
'salt.loader': [
'cloud_dirs=salt_cloud_module_kamatera.loader:clouds_dirs',
],
},
)
|
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):
return '/admin/custom/view/'
def get_edit_url(self):
return '/admin/custom/view/%s/' % self.pk
def get_move_url(self):
return '/admin/custom/move/'
def get_delete_url(self):
return '/admin/custom/delete/%s/' % self.pk
def get_copy_url(self):
return '/admin/custom/copy/'
class TestPluginBetaModel(TestPluginAlphaModel):
"""
NOTE: This is the subject of our test. A plugin which inherits from
another concrete plugin via MTI or Multi-Table Inheritence.
"""
beta = models.CharField('name', blank=False, default='test plugin beta', max_length=32)
|
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)
favorite_users = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True)
def copy_relations(self, other, language):
for favorite_user in other.favorite_users.all():
favorite_user.pk = None
favorite_user.mypageextension = self
favorite_user.save()
extension_pool.register(MyPageExtension)
class MyTitleExtension(TitleExtension):
extra_title = models.CharField(blank=True, default='', max_length=255)
extension_pool.register(MyTitleExtension)
|
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_INHERITANCE_MAGIC
from cms.models import Page, UserSettings
from cms.test_utils.testcases import CMSTestCase, TransactionCMSTestCase
from cms.wizards.wizard_base import Wizard
from cms.wizards.wizard_pool import wizard_pool, AlreadyRegisteredException
class WizardForm(forms.Form):
pass
class ModelWizardForm(ModelForm):
class Meta:
model = UserSettings
exclude = []
class BadModelForm(ModelForm):
class Meta:
pass
class WizardTestMixin(object):
page_wizard = None
title_wizard = None
def assertSequencesEqual(self, seq_a, seq_b):
seq_a = list(seq_a)
seq_b = list(seq_b)
zipped = list(zip(seq_a, seq_b))
if len(zipped) < len(seq_a) or len(zipped) < len(seq_b):
self.fail("Sequence lengths are not the same.")
for idx, (a, b) in enumerate(zipped):
if a != b:
self.fail("Sequences differ at index {0}".format(idx))
@classmethod
def setUpClass(cls):
super(WizardTestMixin, cls).setUpClass()
# This prevents auto-discovery, which would otherwise occur as soon as
# tests start, creating unexpected starting conditions.
wizard_pool._discovered = True
class PageWizard(Wizard):
pass
# This is a basic Wizard
cls.page_wizard = PageWizard(
title=_(u"Page"),
weight=100,
form=WizardForm,
model=Page,
template_name='my_template.html', # This doesn't exist anywhere
)
class SettingsWizard(Wizard):
pass
# This is a Wizard that uses a ModelForm to define the model
cls.user_settings_wizard = SettingsWizard(
title=_(u"UserSettings"),
weight=200,
form=ModelWizardForm,
)
class TitleWizard(Wizard):
pass
# This is a bad wizard definition as it neither defines a model, nor
# uses a ModelForm that has model defined in Meta
cls.title_wizard = TitleWizard(
title=_(u"Page"),
weight=100,
form=BadModelForm,
template_name='my_template.html', # This doesn't exist anywhere
)
class TestWizardBase(WizardTestMixin, TransactionCMSTestCase):
def test_str(self):
self.assertEqual(str(self.page_wizard), self.page_wizard.title)
def test_repr(self):
self.assertEqual(self.page_wizard.__repr__(), 'Wizard: "Page"')
def test_user_has_add_permission(self):
# Test does not have permission
user = self.get_staff_user_with_no_permissions()
self.assertFalse(self.page_wizard.user_has_add_permission(user))
# Test has permission
user = self.get_superuser()
self.assertTrue(self.page_wizard.user_has_add_permission(user))
def test_get_success_url(self):
user = self.get_superuser()
page = create_page(
title="Sample Page",
template=TEMPLATE_INHERITANCE_MAGIC,
language="en",
created_by=smart_text(user),
parent=None,
in_navigation=True,
published=False
)
url = "{0}?edit".format(page.get_absolute_url(language="en"))
self.assertEqual(self.page_wizard.get_success_url(
page, language="en"), url)
# Now again without a language code
url = "{0}?edit".format(page.get_absolute_url())
self.assertEqual(self.page_wizard.get_success_url(page), url)
def test_get_model(self):
self.assertEqual(self.page_wizard.get_model(), Page)
self.assertEqual(self.user_settings_wizard.get_model(), UserSettings)
with self.assertRaises(ImproperlyConfigured):
self.title_wizard.get_model()
class TestWizardPool(WizardTestMixin, CMSTestCase):
def test_discover(self):
wizard_pool._reset()
self.assertFalse(wizard_pool._discovered)
self.assertEqual(len(wizard_pool._entries), 0)
wizard_pool._discover()
self.assertTrue(wizard_pool._discovered)
def test_register_unregister_isregistered(self):
wizard_pool._clear()
self.assertEqual(len(wizard_pool._entries), 0)
wizard_pool.register(self.page_wizard)
# Now, try to register the same thing
with self.assertRaises(AlreadyRegisteredException):
wizard_pool.register(self.page_wizard)
self.assertEqual(len(wizard_pool._entries), 1)
self.assertTrue(wizard_pool.is_registered(self.page_wizard))
self.assertTrue(wizard_pool.unregister(self.page_wizard))
self.assertEqual(len(wizard_pool._entries), 0)
# Now, try to unregister something that is not registered
self.assertFalse(wizard_pool.unregister(self.user_settings_wizard))
def test_get_entry(self):
wizard_pool._clear()
wizard_pool.register(self.page_wizard)
entry = wizard_pool.get_entry(self.page_wizard)
self.assertEqual(entry, self.page_wizard)
def test_get_entries(self):
"""
Test that the registered entries are returned in weight-order, no matter
which order they were added.
"""
wizard_pool._clear()
wizard_pool.register(self.page_wizard)
wizard_pool.register(self.user_settings_wizard)
wizards = [self.page_wizard, self.user_settings_wizard]
wizards = sorted(wizards, key=lambda e: getattr(e, 'weight'))
entries = wizard_pool.get_entries()
self.assertSequencesEqual(entries, wizards)
wizard_pool._clear()
wizard_pool.register(self.user_settings_wizard)
wizard_pool.register(self.page_wizard)
wizards = [self.page_wizard, self.user_settings_wizard]
wizards = sorted(wizards, key=lambda e: getattr(e, 'weight'))
entries = wizard_pool.get_entries()
self.assertSequencesEqual(entries, wizards)
|
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.AlterField(
model_name='globalpagepermission',
name='sites',
field=models.ManyToManyField(help_text='If none selected, user haves granted permissions to all sites.', to='sites.Site', verbose_name='sites', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='usersettings',
name='user',
field=models.OneToOneField(related_name='djangocms_usersettings', editable=False, to=settings.AUTH_USER_MODEL),
preserve_default=True,
),
]
|
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()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.