├── .gitignore └── mysite ├── manage.py ├── myapp ├── __init__.py ├── admin.py ├── apps.py ├── forms.py ├── models.py ├── templates │ ├── form.html │ └── index.html ├── tests.py ├── urls.py └── views.py └── mysite ├── __init__.py ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.toptal.com/developers/gitignore/api/django 2 | # Edit at https://www.toptal.com/developers/gitignore?templates=django 3 | 4 | ### Django ### 5 | *.log 6 | *.pot 7 | *.pyc 8 | __pycache__/ 9 | local_settings.py 10 | db.sqlite3 11 | db.sqlite3-journal 12 | media 13 | 14 | # If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ 15 | # in your Git repository. Update and uncomment the following line accordingly. 16 | # /staticfiles/ 17 | 18 | ### Django.Python Stack ### 19 | # Byte-compiled / optimized / DLL files 20 | *.py[cod] 21 | *$py.class 22 | 23 | # C extensions 24 | *.so 25 | 26 | # Distribution / packaging 27 | .Python 28 | build/ 29 | develop-eggs/ 30 | dist/ 31 | downloads/ 32 | eggs/ 33 | .eggs/ 34 | lib/ 35 | lib64/ 36 | parts/ 37 | sdist/ 38 | var/ 39 | wheels/ 40 | share/python-wheels/ 41 | *.egg-info/ 42 | .installed.cfg 43 | *.egg 44 | MANIFEST 45 | 46 | # PyInstaller 47 | # Usually these files are written by a python script from a template 48 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 49 | *.manifest 50 | *.spec 51 | 52 | # Installer logs 53 | pip-log.txt 54 | pip-delete-this-directory.txt 55 | 56 | # Unit test / coverage reports 57 | htmlcov/ 58 | .tox/ 59 | .nox/ 60 | .coverage 61 | .coverage.* 62 | .cache 63 | nosetests.xml 64 | coverage.xml 65 | *.cover 66 | *.py,cover 67 | .hypothesis/ 68 | .pytest_cache/ 69 | cover/ 70 | 71 | # Translations 72 | *.mo 73 | 74 | # Django stuff: 75 | 76 | # Flask stuff: 77 | instance/ 78 | .webassets-cache 79 | 80 | # Scrapy stuff: 81 | .scrapy 82 | 83 | # Sphinx documentation 84 | docs/_build/ 85 | 86 | # PyBuilder 87 | .pybuilder/ 88 | target/ 89 | 90 | # Jupyter Notebook 91 | .ipynb_checkpoints 92 | 93 | # IPython 94 | profile_default/ 95 | ipython_config.py 96 | 97 | # pyenv 98 | # For a library or package, you might want to ignore these files since the code is 99 | # intended to run in multiple environments; otherwise, check them in: 100 | # .python-version 101 | 102 | # pipenv 103 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 104 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 105 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 106 | # install all needed dependencies. 107 | #Pipfile.lock 108 | 109 | # poetry 110 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 111 | # This is especially recommended for binary packages to ensure reproducibility, and is more 112 | # commonly ignored for libraries. 113 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 114 | #poetry.lock 115 | 116 | # pdm 117 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 118 | #pdm.lock 119 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 120 | # in version control. 121 | # https://pdm.fming.dev/#use-with-ide 122 | .pdm.toml 123 | 124 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 125 | __pypackages__/ 126 | 127 | # Celery stuff 128 | celerybeat-schedule 129 | celerybeat.pid 130 | 131 | # SageMath parsed files 132 | *.sage.py 133 | 134 | # Environments 135 | .env 136 | .venv 137 | env/ 138 | venv/ 139 | ENV/ 140 | env.bak/ 141 | venv.bak/ 142 | 143 | # Spyder project settings 144 | .spyderproject 145 | .spyproject 146 | 147 | # Rope project settings 148 | .ropeproject 149 | 150 | # mkdocs documentation 151 | /site 152 | 153 | # mypy 154 | .mypy_cache/ 155 | .dmypy.json 156 | dmypy.json 157 | 158 | # Pyre type checker 159 | .pyre/ 160 | 161 | # pytype static type analyzer 162 | .pytype/ 163 | 164 | # Cython debug symbols 165 | cython_debug/ 166 | 167 | # PyCharm 168 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 169 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 170 | # and can be added to the global gitignore or merged into this file. For a more nuclear 171 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 172 | #.idea/ 173 | 174 | # End of https://www.toptal.com/developers/gitignore/api/django 175 | -------------------------------------------------------------------------------- /mysite/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /mysite/myapp/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/linder3hs/intro-django/3f988933711cc900f8f634088fe29f8c02b5ae8a/mysite/myapp/__init__.py -------------------------------------------------------------------------------- /mysite/myapp/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import Person 3 | 4 | 5 | admin.site.register(Person) 6 | -------------------------------------------------------------------------------- /mysite/myapp/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class MyappConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'myapp' 7 | -------------------------------------------------------------------------------- /mysite/myapp/forms.py: -------------------------------------------------------------------------------- 1 | from django import forms 2 | 3 | class PersonForm(forms.Form): 4 | 5 | options = [ 6 | ("M", "Masculino"), 7 | ("F", "Femenino"), 8 | ("O", "Otros") 9 | ] 10 | 11 | name = forms.CharField(max_length=200) 12 | address = forms.CharField(max_length=200) 13 | address_2 = forms.CharField(max_length=200) 14 | reference = forms.CharField(max_length=200) 15 | email = forms.EmailField() 16 | password = forms.PasswordInput() 17 | phone_number = forms.CharField(max_length=11) 18 | username = forms.CharField(max_length=50) 19 | gender = forms.ChoiceField(choices=options) 20 | -------------------------------------------------------------------------------- /mysite/myapp/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Tener en cuenta que esto es una clase por ende hay reglas que seguir 4 | # El nombre de mi clase inicia siempre en mayuscula 5 | # Esta clase debe heredar de model.Model 6 | class Person(models.Model): 7 | # Especificar los atributos de mi clase 8 | name = models.CharField(max_length=200) 9 | address = models.CharField(max_length=200) 10 | address_2 = models.CharField(max_length=200, default="") 11 | reference = models.CharField(max_length=200, default="") 12 | email = models.EmailField() 13 | password = models.CharField(max_length=100) 14 | phone_number = models.CharField(max_length=20) 15 | username = models.CharField(max_length=50) 16 | gender = models.CharField(max_length=20) 17 | created_at = models.DateTimeField(auto_now=True) 18 | updated_at = models.DateTimeField(auto_now=True) 19 | 20 | def __str__(self): 21 | return self.name + " " + self.address 22 | 23 | 24 | class PersonProxy(Person): 25 | class Meta: 26 | proxy = True 27 | 28 | def get_full_name(self): 29 | return self.name + " " + self.address 30 | 31 | def get_full_name_and_email(self): 32 | return self.name + " " + self.address + " " + self.email 33 | 34 | 35 | class ValidationPersonProxy(Person): 36 | class Meta: 37 | proxy = True 38 | 39 | def checkpassword(self): 40 | if len(self.password) < 8: 41 | return False 42 | else: 43 | return True 44 | 45 | # Como se usa 46 | # from myapp.models import Person 47 | # person = Person(name="Juan", address="Calle 1", email="juan@juan.com") 48 | # person.save() 49 | 50 | # Como se usa el proxy 51 | # from myapp.models import PersonProxy 52 | # PersonProxy.objects.get(pk=1).get_full_name() # Juan Calle 1 53 | # PersonProxy.objects.get(pk=1).get_full_name_and_email() # Juan Calle 1 juan@juan.com 54 | -------------------------------------------------------------------------------- /mysite/myapp/templates/form.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 |

Creando Personas

11 | 12 |
13 | {% csrf_token %} 14 | {{ form.as_p }} 15 | 16 |
17 | 18 | 19 | -------------------------------------------------------------------------------- /mysite/myapp/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 14 | 15 |

Este es mi primer proyecto con DJango

16 |
17 | 22 |
23 | {% csrf_token %} 24 | {{form}} 25 |
26 | 27 | 28 | -------------------------------------------------------------------------------- /mysite/myapp/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /mysite/myapp/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | from . import views 3 | 4 | urlpatterns = [ 5 | path('', views.Index.as_view(), name='index'), 6 | path('crear/', views.CreatePerson.as_view(), name="crear") 7 | ] 8 | -------------------------------------------------------------------------------- /mysite/myapp/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render, redirect 2 | from .models import Person 3 | from django.views.generic import View, TemplateView, CreateView, FormView 4 | from .forms import PersonForm 5 | 6 | class CreatePerson(FormView): 7 | model = Person 8 | form_class = PersonForm 9 | template_name = "form.html" 10 | 11 | # para guardar la informacion existe lo que es una funcion llamada 12 | def form_valid(self, form): 13 | Person.objects.create(**form.cleaned_data) 14 | return redirect('index') 15 | 16 | def form_invalid(self, form): 17 | print("errors", form.errors) 18 | return redirect('index') 19 | 20 | # class CreatePerson(View): 21 | # def get(self, request): 22 | # context = {"form": PersonForm} 23 | # return render(request, "form.html", context) 24 | 25 | # def post(self, request): 26 | # form = PersonForm(request.POST) 27 | # # vamos a poder acceder a la informacion 28 | # if form.is_valid(): 29 | # # como accedo a la info de los inputs 30 | # # cleaned_data es el objecto que tiene toda la informacion que hemos llenado en los inputs 31 | # # en python es un diccionario 32 | # Person.objects.create(**form.cleaned_data) 33 | # return redirect('index') 34 | # else: 35 | # return redirect('index') 36 | 37 | class TemplateIndexView(CreateView): 38 | template_name = "index.html" 39 | model = Person 40 | fields = ["name", "address", "email"] 41 | extra_context = {"people": Person.objects.all()} 42 | 43 | class Index(View): 44 | # tiene los metodos predefinidos 45 | def get(self, request): 46 | people = Person.objects.all() 47 | context = {"people": people} 48 | return render(request, "index.html", context) 49 | 50 | 51 | # def post(self, request): 52 | # # logica para crear una persona 53 | # Person.objects.create(name=request.POST["name"]) 54 | # return redirect("index") 55 | 56 | 57 | # # Siempre las funciones reciben un request 58 | # def index(request): 59 | # people = Person.objects.all() 60 | # # creando un diccionario 61 | # context = { 62 | # "people": people 63 | # } 64 | 65 | # if request.method == "POST": 66 | # pass 67 | 68 | # # context es una palabra reservada 69 | # # si usamos context al momento de pasar nuestro diccionario de datos 70 | # # unicamente hay que usar el lo keys 71 | # return render(request, "index.html", context) 72 | -------------------------------------------------------------------------------- /mysite/mysite/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/linder3hs/intro-django/3f988933711cc900f8f634088fe29f8c02b5ae8a/mysite/mysite/__init__.py -------------------------------------------------------------------------------- /mysite/mysite/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for mysite project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /mysite/mysite/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for mysite project. 3 | 4 | Generated by 'django-admin startproject' using Django 4.1.3. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.1/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/4.1/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'django-insecure-423b&u^0!@0ln_(42!pt#x(h-n9^+$x%xqyy=o(98m0+dtrran' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'myapp.apps.MyappConfig', 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'mysite.urls' 54 | 55 | TEMPLATES = [ 56 | { 57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 | 'DIRS': [], 59 | 'APP_DIRS': True, 60 | 'OPTIONS': { 61 | 'context_processors': [ 62 | 'django.template.context_processors.debug', 63 | 'django.template.context_processors.request', 64 | 'django.contrib.auth.context_processors.auth', 65 | 'django.contrib.messages.context_processors.messages', 66 | ], 67 | }, 68 | }, 69 | ] 70 | 71 | WSGI_APPLICATION = 'mysite.wsgi.application' 72 | 73 | 74 | # Database 75 | # https://docs.djangoproject.com/en/4.1/ref/settings/#databases 76 | 77 | DATABASES = { 78 | 'default': { 79 | 'ENGINE': 'django.db.backends.mysql', 80 | 'NAME': 'intro_to_django', 81 | 'PORT': '3306', 82 | 'HOST': '127.0.0.1', 83 | 'USER': 'root', 84 | 'PASSWORD': 'root', 85 | } 86 | } 87 | 88 | 89 | # Password validation 90 | # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators 91 | 92 | AUTH_PASSWORD_VALIDATORS = [ 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 101 | }, 102 | { 103 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 104 | }, 105 | ] 106 | 107 | 108 | # Internationalization 109 | # https://docs.djangoproject.com/en/4.1/topics/i18n/ 110 | 111 | LANGUAGE_CODE = 'en-us' 112 | 113 | TIME_ZONE = 'UTC' 114 | 115 | USE_I18N = True 116 | 117 | USE_TZ = True 118 | 119 | 120 | # Static files (CSS, JavaScript, Images) 121 | # https://docs.djangoproject.com/en/4.1/howto/static-files/ 122 | 123 | STATIC_URL = 'static/' 124 | 125 | # Default primary key field type 126 | # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field 127 | 128 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 129 | -------------------------------------------------------------------------------- /mysite/mysite/urls.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.urls import path, include 3 | 4 | urlpatterns = [ 5 | path('admin/', admin.site.urls), 6 | path('myapp/', include('myapp.urls')), 7 | ] 8 | -------------------------------------------------------------------------------- /mysite/mysite/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for mysite project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') 15 | 16 | application = get_wsgi_application() 17 | --------------------------------------------------------------------------------