Skip to content

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
gwens committed Oct 17, 2017
0 parents commit c8c7b7b
Show file tree
Hide file tree
Showing 956 changed files with 63,695 additions and 0 deletions.
27 changes: 27 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
Freeware License, some rights reserved

Copyright (c) 2017 Daniel Rubio

Permission is hereby granted, free of charge, to anyone obtaining a copy
of this software and associated documentation files (the "Software"),
to work with the Software within the limits of freeware distribution and fair use.
This includes the rights to use, copy, and modify the Software for personal use.
Users are also allowed and encouraged to submit corrections and modifications
to the Software for the benefit of other users.

It is not allowed to reuse, modify, or redistribute the Software for
commercial use in any way, or for a user�s educational materials such as books
or blog articles without prior permission from the copyright holder.

The above copyright notice and this permission notice need to be included
in all copies or substantial portions of the software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS OR APRESS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Apress Source Code

This repository accompanies [*Beginning Django*](http://www.apress.com/9781484227862) by Daniel Rubio (Apress, 2017).

[comment]: #cover


Download the files as a zip using the green button, or clone the repository to your machine using Git.

## Releases

Release v1.0 corresponds to the code in the published book, without corrections or updates.

## Contributions

See the file Contributing.md for more information on how you can contribute to this repository.
Empty file.
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib import admin

# Register your models here.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.apps import AppConfig


class AboutConfig(AppConfig):
name = 'about'
87 changes: 87 additions & 0 deletions beginningdjango-master/10_django_users/coffeehouse/about/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
from django import forms
from coffeehouse.about.models import Contact
import re

class GenderField(forms.ChoiceField):
def __init__(self, *args, **kwargs):
super(GenderField, self).__init__(*args, **kwargs)
self.error_messages = {"required":"Please select a gender, it's required"}
self.choices = ((None,'Select gender'),('M','Male'),('F','Female'))

class PlaceholderInput(forms.widgets.Input):
template_name = 'about/placeholder.html'
input_type = 'text'
def get_context(self, name, value, attrs):
context = super(PlaceholderInput, self).get_context(name, value, attrs)
context['widget']['attrs']['maxlength'] = 50
context['widget']['attrs']['placeholder'] = name.title()
return context

class ContactForm(forms.ModelForm):
gender = GenderField()
class Meta:
model = Contact
fields = '__all__'
widgets = {
'name': PlaceholderInput,
'email':PlaceholderInput,
'comment':forms.Textarea
}
error_messages = {
'comment':{"required":"Please, pretty please provide a comment"}
}
labels = {
'email':'Your email'
}
field_order=['email','name','gender','comment']

def __init__(self, *args, **kwargs):
# Get 'initial' argument if any
initial_arguments = kwargs.get('initial', None)
updated_initial = initial_arguments
if initial_arguments:
# We have initial arguments, fetch 'user' placeholder variable if any
user = initial_arguments.get('user',None)
# Now update the form's initial values if user
if user:
updated_initial['name'] = getattr(user, 'first_name', None)
updated_initial['email'] = getattr(user, 'email', None)
# You can also initialize form fields with hardcoded values
# or perform complex DB logic here to then perform initialization
#updated_initial['comment'] = 'Please provide a comment'
# Finally update the kwargs initial reference
kwargs.update(initial=updated_initial)
super(ContactForm, self).__init__(*args, **kwargs)
def clean(self):
# Call clean() method to ensure base class validation
super(ContactForm, self).clean()
# Get the field values from cleaned_data dict
name = self.cleaned_data.get('name','')
email = self.cleaned_data.get('email','')

# Check if the name is part of the email
if name.lower() not in email:
# Name is not in email , raise an error
message = "Please provide an email that contains your name, or viceversa"
#self.add_error('name', message)
#self.add_error('email', forms.ValidationError(message))
self.add_error(None, message)
#raise forms.ValidationError("Please provide an email that contains your name, or viceversa")
def clean_name(self):
# Get the field value from cleaned_data dict
value = self.cleaned_data['name']
# Check if the value is all upper case
if value.isupper():
# Value is all upper case, raise an error
raise forms.ValidationError("Please don't use all upper case for your name, use lower case",code='uppercase')
# Always return value
return value
def clean_email(self):
# Get the field value from cleaned_data dict
value = self.cleaned_data['email']
# Check if the value end in @hotmail.com
if value.endswith('@hotmail.com'):
# Value ends in @hotmail.com, raise an error
raise forms.ValidationError("Please don't use a hotmail email, we simply don't like it",code='hotmail')
# Always return value
return value
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-11 03:47
from __future__ import unicode_literals

import coffeehouse.about.models
from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='Contact',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(blank=True, max_length=50)),
('email', models.EmailField(max_length=254)),
('comment', models.CharField(max_length=1000, validators=[coffeehouse.about.models.validate_comment_word_count])),
],
),
]
Empty file.
23 changes: 23 additions & 0 deletions beginningdjango-master/10_django_users/coffeehouse/about/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible

from django.db import models

from django.core.exceptions import ValidationError

def validate_comment_word_count(value):
count = len(value.split())
if count < 30:
raise ValidationError(('Please provide at least a 30 word message, %(count)s words is not descriptive enough'),
params={'count': count},
)

@python_2_unicode_compatible
class Contact(models.Model):
name = models.CharField(max_length=50,blank=True)
email = models.EmailField()
comment = models.CharField(max_length=1000,validators=[validate_comment_word_count])
def __str__(self):
return "%s" % (self.name)

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<input type="{{ widget.type }}" name="{{ widget.name }}"{% if widget.value != None %} value="{{ widget.value }}"{% endif %}{% include "django/forms/widgets/attrs.html" %} />
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.test import TestCase

# Create your tests here.
12 changes: 12 additions & 0 deletions beginningdjango-master/10_django_users/coffeehouse/about/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.views.generic import TemplateView
from django.conf.urls import url
from . import views

urlpatterns = [
url(r'^$',views.AboutDetail.as_view(),name="index"),
url(r'^(?P<store_id>\d+)/$',views.AboutDetail.as_view(),name="index_withid"),
url(r'^contact/$',views.Contact.as_view(),name="contact"),
url(r'^contact/thankyou$',TemplateView.as_view(template_name='about/thankyou.html'),name="contact_thankyou"),
]
38 changes: 38 additions & 0 deletions beginningdjango-master/10_django_users/coffeehouse/about/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.http import Http404, HttpResponseRedirect
from .forms import ContactForm
from coffeehouse.stores.models import Store
from django.views.generic.detail import DetailView
from django.views import View

class AboutDetail(DetailView):
model = Store
pk_url_kwarg = 'store_id'
template_name = 'about/index.html'
def get_object(self):
if 'store_id' not in self.kwargs:
return Store.objects.get(id=1)
else:
return Store.objects.get(id=self.kwargs['store_id'])

class Contact(View):
# Get handler method
def get(self, request):
form = ContactForm(label_suffix=' : ',initial={'user':request.user,'otherstuff':'otherstuff'},use_required_attribute=False,auto_id=False)
return render(request,'about/contact.html',{'form':form})

# Post handler method
def post(self, request):
# POST, generate form with data from the request
form = ContactForm(request.POST)
# check if it's valid:
if form.is_valid():
# insert into DB
form.save()
# redirect to a new URL:
return HttpResponseRedirect('/about/contact/thankyou')
return render(request,'about/contact.html',{'form':form})

Empty file.
18 changes: 18 additions & 0 deletions beginningdjango-master/10_django_users/coffeehouse/items/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from django.contrib import admin
from coffeehouse.items.models import Menu, Item, Drink

# Register your models here.
class MenuAdmin(admin.ModelAdmin):
pass

admin.site.register(Menu, MenuAdmin)

class ItemAdmin(admin.ModelAdmin):
pass

admin.site.register(Item, ItemAdmin)

class DrinkAdmin(admin.ModelAdmin):
pass

admin.site.register(Drink, DrinkAdmin)
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.apps import AppConfig


class ItemsConfig(AppConfig):
name = 'items'
Loading

0 comments on commit c8c7b7b

Please sign in to comment.