GeorgiLukanov87

How to setup a new DjangoProject_app

May 16th, 2023 (edited)
923
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.62 KB | None | 0 0
  1. # Python Web Basics Retake Exam - 19 April 2022
  2. # 1. GamesPlay App
  3. # https://judge.softuni.org/Contests/Practice/Index/3437#0
  4. """
  5.     After new Django proeject created(using PyCharm Pro + windows10).
  6.    Follow the steps->
  7.  
  8. 1.Execute in terminal -> python manage.py startapp 'name of the app'
  9.    or in manage.py window(CTRL+ALT+R) -> startapp 'name of the app'
  10.    
  11. 2.Move the app to the main project dir.
  12. 3.Create new py-file(urls.py) in the app folder ->
  13.  
  14.     urlpatterns = ()
  15.    
  16.    ->(MUST be tuple! or list!).
  17.    
  18. 4.In settings.py add the app in the 'INSTALLED_APPS'.
  19. 5.Add path to main project urlpatterns -> path('', include('folder_name.my_app_name.urls')),
  20. 6.Run app to see if everything works?
  21.  
  22. 7.Insert the templates in the projects dir.
  23. 8.Create more folders with names like -> for example: core/profile/items and move the templates into.
  24.  
  25. 9.Create a new folder inside the main projects dir with name 'staticfiles'.
  26. 10.In settings.py add additional setting for static dir ->
  27.                                                                STATICFILES_DIRS = (
  28.                                                                    BASE_DIR / 'staticfiles',
  29.                                                                )
  30.  
  31. 11.test to run one of the staticfiles to test if works well.
  32.    For example-> http://127.0.0.1:8000/static/styles/details.css
  33.  
  34.  
  35. 12.In settings.py config database
  36.    -THIS CAN BE DONE IN THE END OF THE TASK(django got default db(sqlite3) connected and works same way!)
  37.    with postgres settings ->
  38.    https://docs.djangoproject.com/en/4.2/ref/settings/#databases
  39.  
  40.                                    DATABASES = {
  41.                                        "default": {
  42.                                            "ENGINE": "django.db.backends.postgresql",
  43.                                            "NAME": "name of the database",
  44.                                            "USER": "postgres user",
  45.                                            "PASSWORD": "mypassword",
  46.                                            "HOST": "127.0.0.1",
  47.                                            "PORT": "5432",
  48.                                        }
  49.                                    }
  50.  
  51. 13.Top right corner Database menu(PyCharm Pro) -> add new -> Data Source -> PostgreSQL -> fill username and password
  52.    then test the connection and connect.
  53.    This is default and do not change it.
  54.    Must be like this ->
  55.                            Host: localhost
  56.                            Port: 5432
  57.                            URL: jdbc:postgresql://localhost:5432/postgres
  58.  
  59.    Now right mouse click on the postgres@localhost and create a new database
  60.    with the correct db name from the settings(step12) -> "NAME":
  61.  
  62.  
  63. 14.Now start the app -> may be you will see error like this ->
  64.            "raise ImproperlyConfigured("Error loading psycopg2 or psycopg module")
  65.            django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 or psycopg module"
  66.  
  67.  
  68. 15.Need to install "psycopg" or "psycopg2" to work correctly.
  69. 16.In terminal execute this -> pip install psycopg2
  70.  
  71. 17.After EVERY! pip install is good to execute-> pip freeze > requiments.txt
  72.    This will create a txt file in your main projects dir
  73.    with name-> 'requiments.txt'
  74.    looking like this ->
  75.                            asgiref==3.6.0
  76.                            Django==4.2.1
  77.                            psycopg2==2.9.6
  78.                            sqlparse==0.4.4
  79.                            tzdata==2023.3
  80.  
  81. 18.You can upgrade your pip -> 'pip install --upgrade pip' (for Windows).
  82.  
  83. 19.Execute in terminal -> "python manage.py migrate"
  84.                            or
  85.    in manage.py window(run it with-> "CTRL+ALT+R", same as step1)  -> "migrate"
  86.    it`s the same , but in manage.py window you have autocomplete and it`s easier.
  87.    Now you can see in your DB the tables filled in. In "db/public/tables"
  88.  
  89. 20.Run to see if everything works well. Good job :D !
  90.  
  91.  
  92. 21.Next step is to add urls paths and config with callable func-views.
  93.    for example->
  94.  
  95.    http://localhost:8000/ - home page
  96.    http://localhost:8000/dashboard/ - dashboard page
  97.  
  98.    http://localhost:8000/game/create/ - create game page
  99.    http://localhost:8000/game/details/<id>/ - details game page
  100.    http://localhost:8000/game/edit/<id>/ - edit game page
  101.    http://localhost:8000/game/delete/<id>/ - delete game page
  102.  
  103.    http://localhost:8000/profile/create - create profile page
  104.    http://localhost:8000/profile/details/ - details profile page
  105.    http://localhost:8000/profile/edit/ - edit profile page
  106.    http://localhost:8000/profile/delete/ - delete profile page
  107.  
  108.  
  109.    -In urls.py looking like this ->
  110.  
  111.                                urlpatterns = (
  112.                                path('', show_index, name='show index'),
  113.                                path('dashboard/', show_dashboard, name='show dashboard'),
  114.  
  115.                                path('profile/', include([
  116.                                    path('create/', create_profile, name='create profile'),
  117.                                    path('details/', details_profile, name='details profile'),
  118.                                    path('edit/', edit_profile, name='edit profile'),
  119.                                    path('delete/', delete_profile, name='delete profile'),
  120.                                ])),
  121.  
  122.                                path('game/', include([
  123.                                    path('create/', create_game, name='create game'),
  124.                                    path('details/<int:pk>/', details_game, name='details game'),
  125.                                    path('edit/<int:pk>/', edit_game, name='edit game'),
  126.                                    path('delete/<int:pk>/', delete_game, name='delete game'),
  127.                                ])),
  128.                            )
  129.  
  130.    -now in views.py ->
  131.  
  132.  
  133.        open -> http://localhost:8000/
  134.        -This is without using PK/ID->
  135.            def show_index(request):
  136.                return render(request, 'core/home-page.html')
  137.  
  138.  
  139.        open -> http://localhost:8000/game/details/1/
  140.        -And this is using PK/ID (hardcoded using value=1, just for testing) ->
  141.            def details_game(request, pk):
  142.                return render(request, 'game/details-game.html')
  143.  
  144.  
  145.    Run to try if working well.
  146.    The pages must visualization without any functionality but rendering.
  147.  
  148.  
  149. 22.Now it`s time to make a superuser(admin) You can reach the link -> http://127.0.0.1:8000/admin/ , and you will see
  150.    the admin panel for loging into the admin panel, but we still miss the superuser.
  151.    Execute in manage.py-> createsuperuser
  152.    and follow the instructions -> fill username,mail,password,repeat password! It`s done.
  153.    Now you can log into admin side.You can create groups and users and giving them permissions and organize all,
  154.    but for now this is enough.
  155.  
  156.  
  157. 23.Time to fix the templates using inheritance.
  158.    In the template directory create a single file with name -> base.html
  159.    This will be the main/base html who will have the base html elements like navigations and footer
  160.    which is repeating in every html.Then we gonna reuse and extend every html with the base.html.
  161.         -{% load static %} this line is when you want to find the staticfiles more accurately.
  162.        Not a 100% required , but it`s recommended.
  163.  
  164.  
  165.    Use this -> to extend the base.html
  166.        {% extends 'base.html' %}
  167.        {% load static %}
  168.        {% block content %}
  169.        {% endblock %}
  170.  
  171.  
  172.    and this in base.html to be the parent to all html elements ->
  173.        {% block content %}
  174.        {# information here #}
  175.        {% endblock %}
  176.  
  177.  
  178.  
  179.    base.html must be looking something like this ->
  180.         base.html STARTS HERE -----------------------------------------------------------------------------
  181.                                {% load static %}
  182.                                <!DOCTYPE html>
  183.                                <html lang="en">
  184.                                <head>
  185.                                    <meta charset="UTF-8">
  186.                                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  187.                                    <link rel="stylesheet" href="{% static '/styles/style.css' %}">
  188.                                    <title>GamesPlay</title>
  189.                                </head>
  190.  
  191.                                <body>
  192.                                <div id="box">
  193.                                    <header>
  194.                                        <h1><a class="home" href="{% url 'show index' %}">GamesPlay</a></h1>
  195.                                        <nav>
  196.                                            <a href="{% url 'create profile' %}">Create Profile</a>
  197.                                            <a href="{% url 'show dashboard' %}">Dashboard</a>
  198.                                            <a href="{% url 'create game' %}">Create Game</a>
  199.                                            <a href="{% url 'details profile' %}">Profile</a>
  200.                                        </nav>
  201.                                    </header>
  202.  
  203.                                    {% block content %}
  204.                                    {# dynamic information here from others html #}
  205.                                    {% endblock %}
  206.  
  207.                                    <footer>
  208.                                        G.Lukanov Team 2023. All rights reserved.
  209.                                    </footer>
  210.  
  211.                                </div>
  212.                                </body>
  213.                                </html>
  214.         base.html ENDS HERE ------------------------------------------------------------------------------------
  215.  
  216.  
  217.  
  218.  
  219.    Example of some the html files which must be looking something like this after inheritance ->
  220.        home-page.html STARTS HERE ------------------------------------------------------------------------------
  221.  
  222.                                    {% extends 'base.html' %}
  223.                                    {% load static %}
  224.                                    {% block content %}
  225.  
  226.                                    <section id="welcome-world">
  227.                                        <div class="welcome-message">
  228.                                            <h2>ALL new games are</h2>
  229.                                            <h3>Only in GamesPlay</h3>
  230.                                        </div>
  231.                                        <img src="{% static '/images/four_slider_img01.png' %}" alt="hero">
  232.                                    </section>
  233.  
  234.                                    {% endblock %}
  235.  
  236.         home-page.html ENDS HERE ---------------------------------------------------------------------------------
  237.  
  238.  
  239.  
  240. This is how finished look -> view.py, models.py and form.py files:
  241.    - views.py -> https://pastebin.com/frzXkpiB
  242.    - models.py -> https://pastebin.com/Cu1p3bGU
  243.    - forms.py -> https://pastebin.com/TujzpDxc
  244.  
  245.  
  246. And above you can see the finished settings.py config.
  247. For sure there are many things to improve , but I hope it helping you! Thanks :)
  248.  
  249. """
  250.  
  251. from pathlib import Path
  252.  
  253. BASE_DIR = Path(__file__).resolve().parent.parent
  254. SECRET_KEY = 'django-insecure-s&yb=i*j3&w37cevb_ip&bijzi7sw^&ukc7((x9^u%+d!lqi3r'
  255. DEBUG = True
  256. ALLOWED_HOSTS = []
  257.  
  258. INSTALLED_APPS = [
  259.     'django.contrib.admin',
  260.     'django.contrib.auth',
  261.     'django.contrib.contenttypes',
  262.     'django.contrib.sessions',
  263.     'django.contrib.messages',
  264.     'django.contrib.staticfiles',
  265.  
  266.     'games_play_app.my_web',
  267. ]
  268.  
  269. MIDDLEWARE = [
  270.     'django.middleware.security.SecurityMiddleware',
  271.     'django.contrib.sessions.middleware.SessionMiddleware',
  272.     'django.middleware.common.CommonMiddleware',
  273.     'django.middleware.csrf.CsrfViewMiddleware',
  274.     'django.contrib.auth.middleware.AuthenticationMiddleware',
  275.     'django.contrib.messages.middleware.MessageMiddleware',
  276.     'django.middleware.clickjacking.XFrameOptionsMiddleware',
  277. ]
  278.  
  279. ROOT_URLCONF = 'games_play_app.urls'
  280.  
  281. TEMPLATES = [
  282.     {
  283.         'BACKEND': 'django.template.backends.django.DjangoTemplates',
  284.         'DIRS': [BASE_DIR / 'templates']
  285.         ,
  286.         'APP_DIRS': True,
  287.         'OPTIONS': {
  288.             'context_processors': [
  289.                 'django.template.context_processors.debug',
  290.                 'django.template.context_processors.request',
  291.                 'django.contrib.auth.context_processors.auth',
  292.                 'django.contrib.messages.context_processors.messages',
  293.             ],
  294.         },
  295.     },
  296. ]
  297.  
  298. WSGI_APPLICATION = 'games_play_app.wsgi.application'
  299.  
  300. # DATABASES = {
  301. #     'default': {
  302. #         'ENGINE': 'django.db.backends.sqlite3',
  303. #         'NAME': BASE_DIR / 'db.sqlite3',
  304. #     }
  305. # }
  306.  
  307. DATABASES = {
  308.     "default": {
  309.         "ENGINE": "django.db.backends.postgresql",
  310.         "NAME": "app_name_db",
  311.         "USER": "postgres",
  312.         "PASSWORD": "some_password",
  313.         "HOST": "127.0.0.1",
  314.         "PORT": "5432",
  315.     }
  316. }
  317.  
  318. AUTH_PASSWORD_VALIDATORS = [
  319.     {
  320.         'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
  321.     },
  322.     {
  323.         'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
  324.     },
  325.     {
  326.         'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
  327.     },
  328.     {
  329.         'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
  330.     },
  331. ]
  332.  
  333. LANGUAGE_CODE = 'en-us'
  334.  
  335. TIME_ZONE = 'UTC'
  336.  
  337. USE_I18N = True
  338.  
  339. USE_TZ = True
  340.  
  341. STATIC_URL = 'static/'
  342.  
  343. STATICFILES_DIRS = (
  344.     BASE_DIR / 'staticfiles',
  345. )
  346.  
  347. DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
  348.  
Add Comment
Please, Sign In to add comment