<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Francisco Alejandro Rojas on Medium]]></title>
        <description><![CDATA[Stories by Francisco Alejandro Rojas on Medium]]></description>
        <link>https://medium.com/@fralejanro?source=rss-a024d8ab6b74------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Francisco Alejandro Rojas on Medium</title>
            <link>https://medium.com/@fralejanro?source=rss-a024d8ab6b74------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:29:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fralejanro/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Deploy Django applications in Heroku]]></title>
            <link>https://fralejanro.medium.com/deploy-django-applications-in-heroku-c8f686d1b3e0?source=rss-a024d8ab6b74------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8f686d1b3e0</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[heroku]]></category>
            <dc:creator><![CDATA[Francisco Alejandro Rojas]]></dc:creator>
            <pubDate>Sun, 07 Feb 2021 19:49:01 GMT</pubDate>
            <atom:updated>2022-02-09T13:08:32.254Z</atom:updated>
            <content:encoded><![CDATA[<p>As the title indicates, this is just one more tutorial on how to deploy django applications in heroku. In this tutorial you will learn a little about everything and a little about nothing, which will lead you to dig into some things that you are simply told to do without going into much detail. Before I start I am going to assume you have Python, pip, Virtualenv, Git and Heroku Cli installed and that you use a version of windows .</p><p>The versions that I use of each tool are the most current at the time of publishing this tutorial, although this does not apply to the git version.</p><ul><li>python 3.9.1</li><li>pip 21.0.1</li><li>virtualenv 20.4.1</li><li>git 2.28.0</li><li>heroku cli 7.47.11</li></ul><p>Let’s go</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FLmNwrBhejkK9EFP504%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FLmNwrBhejkK9EFP504%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcGZ5Z3lrbjNuMzlodnA3ODdrb25wenp2OWNrZjlrYXpibXhua2hpYyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FLmNwrBhejkK9EFP504%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/91c2efa4198c043f3f400f216214650e/href">https://medium.com/media/91c2efa4198c043f3f400f216214650e/href</a></iframe><h4>Create virtual environment, install dependencies, create project and application, initialize repository and create some files necessary for deployment in Heroku</h4><ul><li>Open the command prompt</li><li>Create a folder in which all the project code will be stored</li></ul><pre>C:\Users\fralejanro&gt; mkdir mysite</pre><ul><li>Change to mysite folder and create virtual environment</li></ul><pre>C:\Users\fralejanro&gt; cd mysite<br>C:\Users\fralejanro\mysite&gt; virtualenv mysite_env</pre><ul><li>Activate virtual environment</li></ul><pre>C:\Users\fralejanro\mysite&gt; mysite_env\Scripts\activate</pre><ul><li>Install Django</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite&gt; pip install django</pre><ul><li>Install Whitenoise</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite&gt; pip install whitenoise</pre><ul><li>Install Gunicorn</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite&gt; pip install gunicorn</pre><ul><li>Install dj-database-url</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite&gt; pip install dj-database-url</pre><ul><li>Install Pillow</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite&gt; pip install --upgrade Pillow</pre><ul><li>Install Psycopg2</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite&gt; pip install psycopg2</pre><ul><li>Create a django project</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite&gt; django-admin startproject mysite_project</pre><ul><li>Rename the folder mysite_project to mysite_root and change to the folder mysite_root</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite&gt; ren mysite_project mysite_root<br>(mysite_env) C:\Users\fralejanro\mysite&gt; cd mysite_root</pre><ul><li>Initialize a Git repository</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; git init</pre><ul><li>Create a file to specify the intentionally untracked files that Git should ignore</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; echo. &gt; .gitignore</pre><ul><li>In the .gitignore file write the following</li></ul><pre>*.pyc<br>*.sqlite3<br>.vscode<br>__pycache__/<br>settings_dev.py</pre><ul><li>Create the file that will contain all the dependencies of your project</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; pip freeze &gt; requirements.txt</pre><ul><li>Create a file with the name of runtime.txt and write in it the version of python you are using</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; echo python-3.9.1&gt; runtime.txt</pre><ul><li>Create a file with the name Procfile and define in it the process types and the application entry points</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; echo web: gunicorn mysite_project.wsgi&gt; Procfile</pre><ul><li>Create an application, remember that a project and an application are two different things</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; django-admin startapp blog</pre><ul><li>Create a folder for your base templates and add a .keep file for git to keep track of the folder</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; mkdir templates<br>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; echo. &gt; templates/.keep</pre><ul><li>Create a folder for your static files</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; mkdir static</pre><ul><li>Create a folder for your additional static files and add a .keep file for git to keep track of the folder</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; mkdir staticfiles<br>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; echo. &gt; staticfiles/.keep</pre><ul><li>Create a folder for user uploaded files and add a .keep file for git to keep track of the folder</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; mkdir media<br>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; echo. &gt; media/.keep</pre><h4>Configuring the settings.py file and creating the settings_dev.py file</h4><ul><li>Open the settings.py file from the mysite_project folder with a code editor and make the following modifications</li><li>Add your application to the list of installed applications</li></ul><pre>INSTALLED_APPS = [<br>    &#39;blog.apps.BlogConfig&#39;,<br>    &#39;django.contrib.admin&#39;,<br>    # more apps<br>]</pre><ul><li>Import the os module</li></ul><pre>import os</pre><ul><li>Set the folder path where your base templates are searched</li></ul><pre>TEMPLATES = [<br>    {<br>        &#39;BACKEND&#39;: &#39;django.template.backends.django.DjangoTemplates&#39;,<br>        &#39;DIRS&#39;: [os.path.join(BASE_DIR, &#39;templates&#39;)],<br>        # ...</pre><ul><li>Set the folder path where your static files are stored after using <strong>python manage.py collectstatic</strong></li></ul><pre>STATIC_ROOT = os.path.join(BASE_DIR, &#39;static&#39;)</pre><ul><li>Set the folder path where your additional static files are stored</li></ul><pre>STATICFILES_DIRS = [<br>    os.path.join(BASE_DIR, &#39;staticfiles&#39;),<br>]</pre><ul><li>Set the folder path where user uploaded files will go</li></ul><pre>MEDIA_URL = &#39;/media/&#39;<br>MEDIA_ROOT  = os.path.join(BASE_DIR, &#39;media&#39;)</pre><ul><li>Enable Whitenoise. The WhiteNoise middleware should be placed directly after Django SecurityMiddleware (if you are using it) and before any other middleware</li></ul><pre>MIDDLEWARE = [<br>    &#39;django.middleware.security.SecurityMiddleware&#39;,<br>    &#39;whitenoise.middleware.WhiteNoiseMiddleware&#39;,<br>    # ...<br>]</pre><ul><li>Add compression and caching support</li></ul><pre>STATICFILES_STORAGE = &#39;whitenoise.storage.CompressedManifestStaticFilesStorage&#39;</pre><ul><li>Configure the proxy to set a custom HTTP header that tells Django if the request came through HTTPS</li></ul><pre>SECURE_PROXY_SSL_HEADER = (&#39;HTTP_X_FORWARDED_PROTO&#39;, &#39;https&#39;)</pre><ul><li>At this point you need to create a copy of the settings.py file that is located inside the mysite_project folder, save the copy with the name of settings_dev.py in the mysite_project folder</li><li>Configure the local postgresql database, in the settings_dev.py file located inside the mysite_project folder. This is only necessary if you are not using the default sqlite database</li></ul><pre>DATABASES = {<br>    &#39;default&#39;: {<br>        &#39;ENGINE&#39;: &#39;django.db.backends.postgresql_psycopg2&#39;,<br>        &#39;NAME&#39;: &#39;your_database&#39;,<br>        &#39;USER&#39;: &#39;postgres&#39;,<br>        &#39;PASSWORD&#39;: &#39;your_password&#39;,<br>        &#39;HOST&#39;: &#39;localhost&#39;,<br>        &#39;PORT&#39;: &#39;5432&#39;,<br>    }<br>}</pre><p>Now continue editing the settings.py file found in the mysite_project folder</p><ul><li>Configure the heroku database with the dj-database-url library</li></ul><pre>import dj_database_url</pre><pre>DATABASES = {<br>    &#39;default&#39;: dj_database_url.config(conn_max_age=600, ssl_require=True)<br>}</pre><ul><li>Set the SECRET_KEY so that its value is set from a Heroku config var</li></ul><pre>SECRET_KEY = os.getenv(&#39;SECRET_KEY&#39;)</pre><ul><li>Change the value of DEBUG to False and set allowed hosts</li></ul><pre>DEBUG = False<br>    <br>ALLOWED_HOSTS = [&#39;.herokuapp.com&#39;]</pre><h4>Configuring the urls</h4><ul><li>Create a file with the name of urls.py in the blog folder</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; cd blog<br>(mysite_env) C:\Users\fralejanro\mysite\mysite_root\blog&gt; echo. &gt; urls.py</pre><ul><li>Open the file you just created and type the following</li></ul><pre>from django.urls import path<br>from django.conf import settings<br>from django.conf.urls.static import static<br>from . import views<br>    <br>urlpatterns = [</pre><pre>]</pre><pre>urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)<br>urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)</pre><ul><li>Now open the urls.py file found in the mysite_project folder and add a url to get the urls from the urls.py file of the blog application</li></ul><pre>from django.contrib import admin<br>from django.urls import path, include</pre><pre>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;&#39;, include(&#39;blog.urls&#39;)),<br>]</pre><h4>Collect static files and migrate</h4><ul><li>Change to mysite_root folder and collect static files</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root\blog&gt; cd ..<br>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; python manage.py collectstatic --settings=mysite_project.settings_dev</pre><ul><li>Migrate</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; python manage.py migrate --settings=mysite_project.settings_dev</pre><p>You’re almost done, just a few more steps</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o7TKEP6YngkCKFofC%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o7TKEP6YngkCKFofC%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExN282bmR6cWp4Y3RkdGdzOW9sbm1seXF5OXRlOGtyY2E0OWplZ25ubSZlcD12MV9naWZzX2dpZklkJmN0PWc%2F3o7TKEP6YngkCKFofC%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="328" frameborder="0" scrolling="no"><a href="https://medium.com/media/afb6b9740b42f6ea895220040c234c8a/href">https://medium.com/media/afb6b9740b42f6ea895220040c234c8a/href</a></iframe><h4>Commit, create app, config vars and deploy in Heroku</h4><ul><li>Add files to trace and make your first commit</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; git add .<br>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; git commit -m &quot;Init App&quot;</pre><ul><li>Login to heroku</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; heroku login</pre><ul><li>Create a new application in heroku with a Python build package</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt;heroku create mysitemedium --buildpack heroku/python</pre><ul><li>Create a var for your SECRET_KEY, the value of the SECRET_KEY is in the settings_dev.py file that is inside the mysite_project folder. The value of the SECRET_KEY must be enclosed in quotes, the quotes are not part of the SECRET_KEY</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; heroku config:set SECRET_KEY=&quot;your_secret_key&quot; -a mysitemedium</pre><ul><li>Create a var so that heroku does not execute collectstatic and does not serve its static files</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; heroku config:set DISABLE_COLLECTSTATIC=1 -a mysitemedium</pre><ul><li>Add a remote control to the local repository with the name of the application</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; heroku git:remote -a mysitemedium<br>set git remote heroku to <a href="https://git.heroku.com/mysitemedium.git">https://git.heroku.com/mysitemedium.git</a></pre><ul><li>Use the command to insert the code of the master branch of the local repository into the remote of heroku</li></ul><pre>(mysite_env) C:\Users\fralejanro\mysite\mysite_root&gt; git push heroku master<br>Enumerating objects: 306, done.<br>Counting objects: 100% (306/306), done.<br>Delta compression using up to 2 threads<br>Compressing objects: 100% (299/299), done.<br>Writing objects: 100% (306/306), 989.00 KiB | 142.00 KiB/s, done.<br>Total 306 (delta 37), reused 0 (delta 0), pack-reused 0<br>remote: Compressing source files... done.<br>remote: Building source:<br>remote:<br>remote: -----&gt; Building on the Heroku-20 stack<br>remote: -----&gt; Python app detected<br>remote: -----&gt; Installing python-3.9.1<br>remote: -----&gt; Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2<br>remote: -----&gt; Installing SQLite3<br>remote: -----&gt; Installing requirements with pip<br>remote:        Collecting asgiref==3.3.1<br>remote:          Downloading asgiref-3.3.1-py3-none-any.whl (19 kB)<br>remote:        Collecting Django==3.1.6<br>remote:          Downloading Django-3.1.6-py3-none-any.whl (7.8 MB)<br>remote:        Collecting gunicorn==20.0.4<br>remote:          Downloading gunicorn-20.0.4-py2.py3-none-any.whl (77 kB)<br>remote:        Collecting Pillow==8.1.0<br>remote:          Downloading Pillow-8.1.0-cp39-cp39-manylinux1_x86_64.whl (2.2 MB)<br>remote:        Collecting psycopg2==2.8.6<br>remote:          Downloading psycopg2-2.8.6.tar.gz (383 kB)<br>remote:        Collecting pytz==2021.1<br>remote:          Downloading pytz-2021.1-py2.py3-none-any.whl (510 kB)<br>remote:        Collecting sqlparse==0.4.1<br>remote:          Downloading sqlparse-0.4.1-py3-none-any.whl (42 kB)<br>remote:        Collecting whitenoise==5.2.0<br>remote:          Downloading whitenoise-5.2.0-py2.py3-none-any.whl (19 kB)<br>remote:        Building wheels for collected packages: psycopg2<br>remote:          Building wheel for psycopg2 (setup.py): started<br>remote:          Building wheel for psycopg2 (setup.py): finished with status &#39;done&#39;<br>remote:          Created wheel for psycopg2: filename=psycopg2-2.8.6-cp39-cp39-linux_x86_64.whl size=523826 sha256=34d4bb8d577ff4b3800538fb53098c6e917e07d6bf12662678c25b4821ca67c1<br>remote:          Stored in directory: /tmp/pip-ephem-wheel-cache-oqpf3z_g/wheels/a2/07/10/a9a82e72d50feb8d646acde6a88000bbf2ca0f82e41aea438a<br>remote:        Successfully built psycopg2<br>remote:        Installing collected packages: asgiref, pytz, sqlparse, Django, gunicorn, Pillow, psycopg2, whitenoise<br>remote:        Successfully installed Django-3.1.6 Pillow-8.1.0 asgiref-3.3.1 gunicorn-20.0.4 psycopg2-2.8.6 pytz-2021.1 sqlparse-0.4.1 whitenoise-5.2.0<br>remote: -----&gt; Discovering process types<br>remote:        Procfile declares types -&gt; web<br>remote:<br>remote: -----&gt; Compressing...<br>remote:        Done: 62.9M<br>remote: -----&gt; Launching...<br>remote:        Released v7<br>remote:        <a href="https://mysitemedium.herokuapp.com/">https://mysitemedium.herokuapp.com/</a> deployed to Heroku<br>remote:<br>remote: Verifying deploy... done.<br>To <a href="https://git.heroku.com/mysitemedium.git">https://git.heroku.com/mysitemedium.git</a><br> * [new branch]      master -&gt; master</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FwZjlCH43M3M0U%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FwZjlCH43M3M0U%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExNGthNW8yaDhsdTJvam85anZjdHBzOTY2bTVsdXV5bG1jbWxiZHVxOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FwZjlCH43M3M0U%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="239" frameborder="0" scrolling="no"><a href="https://medium.com/media/f05fa4786dec7c0f34036a50c8168458/href">https://medium.com/media/f05fa4786dec7c0f34036a50c8168458/href</a></iframe><p>If you have an output like the previous one, it means that you already have your Django application deployed in Heroku. To verify this, you can enter the administrator view of your application, your url should be similar to this <a href="https://mysitemedium.herokuapp.com/admin">https://mysitemedium.herokuapp.com/admin</a>, since if you enter only your application you will get “The requested resource was not found on this server.” And it is good that this happens since we do not define any associated view that url.</p><p>All the application code is in the following repository <a href="https://github.com/fralejanro/mysite">fralejanro/mysite: Deploy Django applications in Heroku (github.com)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8f686d1b3e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Alternative to Django Crispy Forms]]></title>
            <link>https://fralejanro.medium.com/alternative-to-django-crispy-forms-2e910e39744b?source=rss-a024d8ab6b74------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e910e39744b</guid>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[bootstrap-4]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Francisco Alejandro Rojas]]></dc:creator>
            <pubDate>Mon, 02 Nov 2020 22:02:00 GMT</pubDate>
            <atom:updated>2020-11-02T22:02:00.118Z</atom:updated>
            <content:encoded><![CDATA[<p>Two years ago I started developing applications with Django and bootstrap 4 and I found that this framework has a very particular way of working with the rendering of forms. At first it was very easy to render the forms since Django provides three options to render them and with the simple fact of writing a line of code I already had a form rendered with all its fields in one column.</p><p><a href="https://docs.djangoproject.com/en/3.1/topics/forms/#form-rendering-options">Working with forms | Django documentation | Django</a></p><p>However, having more complex forms, these options did not satisfy my needs, so I began to investigate and found that in many cases <a href="https://django-crispy-forms.readthedocs.io/en/latest/">Django Crispy Forms</a> was used, which is an application that allows you to manage forms, adjust the properties of the forms among other functions, but I did not want to do this as with the options provided by Django everything was done in a very transparent, way which did not allow me to have all the control over what I was doing. So I tried to make an alternative that in the beginning I posted in a Stackoverflow <a href="https://stackoverflow.com/questions/55072876/alternative-to-django-crispy-forms">question</a> and that I’m posting here today.</p><p>For this example what I wanted was to have a form similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*2Ysx51DW1ntp-fg43eHlsA.png" /><figcaption><a href="https://getbootstrap.com/docs/4.3/components/forms/#server-side">https://getbootstrap.com/docs/4.3/components/forms/#server-side</a></figcaption></figure><p>The first thing is that I am making use of a form from a model, that is, it is a form in which it is not necessary to define the types of fields of the form (unless you need to customize it) since it is based on a model the fields take the types of the model. My model and form looks like this:</p><p><strong>models.py</strong></p><pre>class User(models.Model):</pre><pre>GENDER = (<br>        (&#39;0&#39;, &#39;Female&#39;),<br>        (&#39;1&#39;, &#39;Male&#39;),<br>    )<br>    code = models.AutoField(primary_key=True<br>    username = models.CharField(unique=True, max_length=100)<br>    first_name = models.CharField(max_length=100)<br>    last_name = models.CharField(max_length=100)<br>    age = models.DateField()<br>    email = models.EmailField(unique=True)<br>    password = models.CharField(max_length=25)<br>    gender = models.CharField(max_length=1, choices=GENDER)</pre><p><strong>forms.py</strong></p><pre>from django.forms import ModelForm<br>from blog.models import User</pre><pre>GENDER = (<br>        (&#39;0&#39;, &#39;Female&#39;),<br>        (&#39;1&#39;, &#39;Male&#39;),<br>    )</pre><pre>class SignupForm(ModelForm):</pre><pre>class Meta:<br>        model = User<br>        fields = [&#39;username&#39;, &#39;first_name&#39;,&#39;last_name&#39;, &#39;age&#39;, &#39;email&#39;, &#39;password&#39;, &#39;gender&#39;]<br>        widgets = {<br>            &#39;age&#39;: forms.DateInput(attrs={&#39;class&#39;: &#39;form-control&#39;, &#39;type&#39;: &#39;date&#39;}),<br>            &#39;gender&#39;: forms.Select(attrs={&#39;class&#39;: &#39;form-control&#39;}, choices=GENDER),<br>        }<br>        labels = {<br>            &#39;username&#39;: (&#39;Username&#39;),<br>            &#39;first_name&#39;: (&#39;First name&#39;),<br>            &#39;last_name&#39;: (&#39;Last name&#39;),<br>            &#39;age&#39;: (&#39;Age&#39;),<br>            &#39;email&#39;: (&#39;Email&#39;),<br>            &#39;password&#39;: (&#39;Password&#39;),<br>            &#39;gender&#39;: (&#39;Gender&#39;),<br>        }<br>        error_messages = {<br>            &#39;username&#39;: {<br>                &#39;required&#39;: (&#39;The field username can not be empty&#39;),<br>                &#39;unique&#39;: (&#39;The username is not available&#39;)<br>            },<br>            &#39;first_name&#39;: {<br>                &#39;required&#39;: (&#39;The field first name can not be empty&#39;)<br>            },<br>            &#39;last_name&#39;: {<br>                &#39;required&#39;: (&#39;The field last name can not be empty&#39;)<br>            },<br>            &#39;password&#39;: {<br>                &#39;required&#39;: (&#39;The field password can not be empty&#39;)<br>            }<br>         }<br>    def __init__(self, *args, **kwargs):<br>        super(SignupForm, self).__init__(*args, **kwargs)<br>            for field in iter(self.fields):<br>                if field != &#39;age&#39; and field != &#39;gender&#39;:<br>                    self.fields[field].widget.attrs.update({<br>                        &#39;class&#39;: &#39;form-control&#39;,<br>                })</pre><p>Now, let’s explain everything that happened in Forms.py</p><ul><li>We import ModelForm, which as I said before we are using a form from a model, and we import User which is the model bound to the form.</li><li>In the meta class we assign the model attribute to the model attribute that we are going to use in this case User</li><li>In the fields attribute we define a list with the fields that we want to be displayed in the form</li><li>In the widgets attribute we assign a dictionary that contains the <a href="https://docs.djangoproject.com/en/3.1/ref/forms/widgets/">widgets</a> associated with each field of the form, this is only necessary for the new fields that we add to the form or for the fields that we customize. For this case we customize the age fields to which in its attributes we assign a class and a type and the gender field to which in its attributes we assign a class and apart from this, some choices. We add a class to both because it is necessary for use bootstrap. Remember that a widget in essence is representation of an HTML input element.</li><li>In the labels attribute we define a dictionary that contains the labels associated with each field of the form</li><li>In the error_messages attribute we define a dictionary that contains the error messages associated with each field of the form, this invalidates the error messages that match those that Django provides by default</li><li>Override the __init__ function of the form to assign the value of the class to all the fields that were not personalized, this is done by going through each field of the form and updating the value of attrs of each widget</li></ul><p>Now you only need to import and use the form that we just created in the views and create the template to have the final result.</p><p><strong>views.py</strong></p><pre>from django.shortcuts import render,redirect<br>from .forms import SignupForm</pre><pre>def sign_up(request):<br>    if request.method == &#39;POST&#39;:<br>        form = SignupForm(request.POST)<br>        if form.is_valid():<br>            return redirect(&#39;home&#39;)<br>        else:<br>            change_class_for_error(form)<br>            return render(request, &#39;blog/signup.html&#39;, {&#39;form&#39;: form})<br>    else:<br>        form = SignupForm()<br>        return render(request, &#39;blog/signup.html&#39;, {&#39;form&#39;: form})</pre><pre>def change_class_for_error(form):<br>    for field in form:<br>        if field.errors:<br>            form.fields[field.name].widget.attrs[&#39;class&#39;] = &#39;form-control is-invalid&#39;</pre><p>Here in the view, the only thing we did was create a function called change_class_for_error that receives the form and that is in charge of going through each field of the form and if any of them presents an error, update the value of the ‘class’ in the attrs dictionary of each widget. This function is only called if the form is invalid.</p><p>Finally we have the template.</p><p><strong>signup.html</strong></p><pre>&lt;div class=&quot;row justify-content-center&quot; style=&quot;padding-top: 1rem&quot;&gt;<br>     &lt;div class=&quot;col-md-10&quot;&gt;<br>         &lt;div class=&quot;card&quot;&gt;<br>             &lt;div class=&quot;card-header text-center&quot;&gt;Sign up&lt;/div&gt;<br>             &lt;div class=&quot;card-body&quot;&gt;<br>                 &lt;form method=&quot;POST&quot;&gt;<br>                     {% csrf_token %}<br>                     &lt;div class=&quot;form-row&quot;&gt;<br>                         &lt;div class=&quot;form-group col-md-4&quot;&gt;<br>                             &lt;label &gt;{{ form.username.label }}&lt;/label&gt;<br>                             {{ form.username }}<br>                             {% for error in form.username.errors %}<br>                                 &lt;div class=&quot;invalid-feedback&quot;&gt;{{ error }}&lt;/div&gt;<br>                             {% endfor %}<br>                         &lt;/div&gt;</pre><pre>&lt;div class=&quot;form-group col-md-4&quot;&gt;<br>                             &lt;label&gt;{{ form.first_name.label }}&lt;/label&gt;<br>                             {{ form.first_name }}<br>                             {% for error in form.first_name.errors %}<br>                                 &lt;div class=&quot;invalid-feedback&quot;&gt;{{ error }}&lt;/div&gt;<br>                             {% endfor %}<br>                         &lt;/div&gt;</pre><pre>&lt;div class=&quot;form-group col-md-4&quot;&gt;<br>                             &lt;label&gt;{{ form.last_name.label }}&lt;/label&gt;<br>                             {{ form.last_name }}<br>                             {% for error in form.last_name.errors %}<br>                                 &lt;div class=&quot;invalid-feedback&quot;&gt;{{ error }}&lt;/div&gt;<br>                             {% endfor %}<br>                         &lt;/div&gt;<br>                     &lt;/div&gt;</pre><pre>&lt;div class=&quot;form-row&quot;&gt;<br>                         &lt;div class=&quot;form-group col-md-4&quot;&gt;<br>                             &lt;label &gt;{{ form.age.label }}&lt;/label&gt;<br>                             {{ form.age }}<br>                             {% for error in form.age.errors %}<br>                                 &lt;div class=&quot;invalid-feedback&quot;&gt;{{ error }}&lt;/div&gt;<br>                             {% endfor %}<br>                         &lt;/div&gt;</pre><pre>&lt;div class=&quot;form-group col-md-4&quot;&gt;<br>                             &lt;label &gt;{{ form.gender.label }}&lt;/label&gt;<br>                             {{ form.gender }}<br>                             {% for error in form.gender.errors %}<br>                                 &lt;div class=&quot;invalid-feedback&quot;&gt;{{ error }}&lt;/div&gt;<br>                             {% endfor %}<br>                         &lt;/div&gt;</pre><pre>&lt;div class=&quot;form-group col-md-4&quot;&gt;<br>                             &lt;label &gt;{{ form.country.label }}&lt;/label&gt;<br>                             {{ form.country}}<br>                             {% for error in form.country.errors %}<br>                                 &lt;div class=&quot;invalid-feedback&quot;&gt;{{ error }}&lt;/div&gt;<br>                             {% endfor %}<br>                         &lt;/div&gt;<br>                     &lt;/div&gt;</pre><pre>&lt;div class=&quot;form-row&quot;&gt;<br>                         &lt;div class=&quot;form-group col-md-6&quot;&gt;<br>                             &lt;label &gt;{{ form.email.label }}&lt;/label&gt;<br>                             {{ form.email }}<br>                              {% for error in form.email.errors %}<br>                                 &lt;div class=&quot;invalid-feedback&quot;&gt;{{ error }}&lt;/div&gt;<br>                             {% endfor %}<br>                         &lt;/div&gt;</pre><pre>&lt;div class=&quot;form-group col-md-6&quot;&gt;<br>                             &lt;label &gt;{{ form.password.label }}&lt;/label&gt;<br>                             {{ form.password }}<br>                              {% for error in form.password.errors %}<br>                                 &lt;div class=&quot;invalid-feedback&quot;&gt;{{ error }}&lt;/div&gt;<br>                             {% endfor %}<br>                         &lt;/div&gt;<br>                     &lt;/div&gt;</pre><pre>&lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Sign in&lt;/button&gt;<br>                 &lt;/form&gt;<br>             &lt;/div&gt;<br>         &lt;/div&gt;<br>     &lt;/div&gt;<br> &lt;/div&gt;</pre><p>In the template we have a cycle that goes through each field of the form and for each field of the form we obtain its label and use a cycle to go through the errors it presents</p><p>The result :]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTdoVKPruFgxN8uDvsaKkQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e910e39744b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>