Search This Blog

Thursday, October 17, 2024

How to run Django Applications in Https directly - SSL - Openssl or CA certificate

 Here is the simple steps.

1. Either you can use mkcert or openssl.


2. openssl req -newkey rsa:4096 \

            -x509 \

            -sha256 \

            -days 365 \

            -nodes \

            -out ordersbts.crt \

            -keyout ordersbts.key \

            -subj "/C=SI/ST=KARNATAKA/L=BANGALORE/O=ArsenaiT/OU=ITServices/CN=ourapp.arsenalit.com"


3. Configuring Django server to work with HTTPS

The default Django manage.py runserver command doesn't support SSL; therefore, we need to use the alternative manage.py runserver_plus command, which is part of the excellent Django Extensions package.

Run the following command to install Django extensions alongwith the Wekzeug server:

pip install django-extensions Werkzeug

The runserver_plus command requires installation of the Werkzeug server, which is better known in the world of the Python Framework Flask.


Next, open the settings.py file in your code editor and add django_extensions to the INSTALLED_APPS list:


settings.py

NSTALLED_APPS = [

    # other apps

    "django_extensions",

]

Finally, start the local development server in HTTPS mode by running the command:

nohup python3.9 manage.py runserver_plus --cert-file httpskeys/myapp.crt --key-file httpskeys/myapp.key 0.0.0.0:443 &


And that's it; you should now see the local development server running at the default https://localhost:443 address.


If any error comes, 

1. Delete your virtual environment folder and Recreate it. 

       sudo rm -r venv3.9

        python3.9 -m venv env3.9

       deactivate

       source env3.9/bin/activate


2. Run your libraries with pip install -r requirements.txt

3. excute python3.9 manage.py [above command]


ENJOY


For mkcert use this following link https://timonweb.com/django/https-django-development-server-ssl-certificate/


Sunday, July 7, 2024

Send Email from Django Project with Domain HostMyCode SMTP

 url.py

from django.contrib import admin

from django.urls import path

from my_app import views


urlpatterns = [

    path('admin/', admin.site.urls),

    path('',views.index, name="homepage"),

    path('send-email/', views.send_test_email, name='send_email'),

]


settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'mail.arsenalit.com'  # Replace with your SMTP host
EMAIL_PORT = 587  # Usually 587 for TLS
EMAIL_USE_TLS = True  # Use TLS for secure connection
EMAIL_USE_SSL = False  # Set to False if using TLS
EMAIL_HOST_USER = 'email@arsenalit.com'  # Your SMTP username/email
EMAIL_HOST_PASSWORD = 'password'  # Your SMTP email password
DEFAULT_FROM_EMAIL = 'from@arsenalit.com'  # Default from email
EMAIL_TIMEOUT = 60


views.py

def send_test_email(request):
    #import pdb;
    #pdb.set_trace();
    subject = 'Test Email'
    message = 'This is a test email sent from Django using HostMyCode SMTP server.'
    from_email = 'from@arsenalit.com'
    recipient_list = ['toemail@gmail.com']
    
    try:
        print ( "calling send Email");
        send_mail(subject, message, from_email, recipient_list)
        return HttpResponse('Email sent successfully')
    except Exception as e:
        return HttpResponse(f'Error sending email: {e}')
        

Tuesday, February 27, 2024

Python Create Virtual Environment Windows & Linux

 1. install your python exe or python version 

2. check python --version or py --version and keep that in mind to use it


windows

   python --version

   pip install virtualenv 

#here python --version says 3.9, then while creating Venv, use python or python3.9 which ever works

   python -m venv env3.9

   env3.9\Scripts\activate

   deactivate


linux

sudo apt install python3.9

sudo apt install python3.9-venv

python3.9 --version

python3.9 -m venv env3.9

source env3.9/bin/activate

deactivate

Thursday, January 4, 2024

HTML Forms Fields - Auto Save Later Using LocalStorage

Step 1: Create 3 file in the name of 

            index.html

            form.js

            form.css


Step 2: below are the code for 3 files

Step 3: once created, open index.html in browser. 

               Type some thing in field. CLICK SAVE. close the browser, open the browser again and type the index.html url. you can see the previous typed msg.



index.html

<!-- index.html -->

<!DOCTYPE html>

<html lang="en">

  <head>

    <meta charset="UTF-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <meta http-equiv="X-UA-Compatible" content="ie=edge" />

    <link rel="stylesheet" href="form.css" />

    <title>Save Later</title>

  </head>

  <body>

    <div class="alert"></div>

    <form id="save-later-form">

      <h3>Simple Save Later Form</h3>

      <label for="full-name">Full Name</label>

      <input type="text" name="full-name" id="full-name" />

      <label for="email">Email</label>

      <input type="email" name="email" id="email" />

      <label for="phone">Phone Number</label>

      <input type="tel" name="phone" id="phone" maxlength="11" />

      <label for="dob">Date Of Birth</label>

      <input type="date" name="dob" id="dob" />

      <label for="security">Security Question</label>

      <select name="security" id="security" tabindex="0">

        <option value="">Select a question</option>

        <option value="best-friend">What's your best friend's name?</option>

        <option value="pet">What's the name of your first pet?</option>

        <option value="spouse">Where did you meet your spouse?</option>

      </select>

      <label for="security-answer">Answer</label>

      <input type="text" name="security-answer" id="security-answer" />

      <label for="description">Description</label>

      <textarea

        name="description"

        id="description"

        placeholder="Describe yourself in 100 words"

      ></textarea>

      <button type="submit" id="submit">SUBMIT</button>

      <button type="submit" id="save">SAVE</button>

    </form>

  </body>

  <script src="form.js"></script>

</html>



form.js

// form.js

const formId = "save-later-form"; // ID of the form

const url = location.href; //  href for the page

const formIdentifier = `${url} ${formId}`; // Identifier used to identify the form

const saveButton = document.querySelector("#save"); // select save button

const alertBox = document.querySelector(".alert"); // select alert display div

let form = document.querySelector(`#${formId}`); // select form

let formElements = form.elements; // get the elements in the form


/**

 * This function gets the values in the form

 * and returns them as an object with the

 * [formIdentifier] as the object key

 * @returns {Object}

 */

const getFormData = () => {

  let data = { [formIdentifier]: {} };

  for (const element of formElements) {

    if (element.name.length > 0) {

      data[formIdentifier][element.name] = element.value;

    }

  }

  return data;

};


saveButton.onclick = event => {

  event.preventDefault();

  data = getFormData();

  localStorage.setItem(formIdentifier, JSON.stringify(data[formIdentifier]));

  const message = "Form draft has been saved!";

  displayAlert(message);

};


/**

 * This function displays a message

 * on the page for 1 second

 *

 * @param {String} message

 */

const displayAlert = message => {

  alertBox.innerText = message;

  alertBox.style.display = "block";

  setTimeout(function() {

    alertBox.style.display = "none";

  }, 1000);

};


/**

 * This function populates the form

 * with data from localStorage

 *

 */

const populateForm = () => {

  if (localStorage.key(formIdentifier)) {

    const savedData = JSON.parse(localStorage.getItem(formIdentifier)); // get and parse the saved data from localStorage

    for (const element of formElements) {

      if (element.name in savedData) {

        element.value = savedData[element.name];

      }

    }

    const message = "Form has been refilled with saved data!";

    displayAlert(message);

  }

};


document.onload = populateForm(); // populate the form when the document is loadedd


form.css

/* form.css */

@import url("https://fonts.googleapis.com/css?family=Nunito");


*,

*:before,

*:after {

  box-sizing: border-box;

}


body {

  background-color: whitesmoke;

  font-family: "Nunito", sans-serif;

}


h3,

label {

  text-transform: uppercase;

}


.alert {

  width: 80vw;

  margin: 2rem auto;

  background-color: #d4edda;

  color: #155724;

  padding: 0.75rem 1.25rem;

  border-radius: 0.25rem;

  display: none;

}


#save-later-form {

  position: relative;

  width: 80vw;

  margin: 3rem auto;

  background-color: white;

  padding: 1rem 2rem;

  border-radius: 3px;

}


label {

  margin: 1rem 0 0;

  display: block;

}


input {

  font-size: 0.875em;

  width: 100%;

  height: 40px;

  padding: 0px 15px 0px 15px;

  background: whitesmoke;

  outline: none;

  color: #000;

  border: none;

  border-radius: 3px;

}


input:hover {

  background: whitesmoke;

  color: black;

}


button[type="submit"] {

  background-color: #349bab;

  width: calc((100% / 2) - 3px);

  display: inline-block;

  color: white;

  font-weight: 600;

  height: 2.8rem;

  border: none;

  font-family: Nunito;

  font-size: 1rem;

  cursor: pointer;

  outline: none;

}


#save {

  background-color: #30383f;

}


select {

  width: 100%;

  height: 40px;

  background: whitesmoke;

  border: none;

  padding: 0 0 0 0.5rem;

  outline: none;

}


select:focus,

input:focus,

textarea:focus {

  outline: #349bab solid 1px;

}


textarea {

  width: 100%;

  max-width: 100%;

  height: 110px;

  max-height: 110px;

  padding: 15px;

  margin: 0 0 1rem 0;

  background: whitesmoke;

  outline: none;

  color: black;

  font-size: 0.875em;

  border: none;

}

/* ========MEDIA QUERIES======== */

@media screen and (min-width: 768px) {

  #save-later-form,

  .alert {

    width: 60vw;

  }

}


@media screen and (min-width: 992px) {

  #save-later-form,

  .alert {

    width: 40vw;

  }

}



Sample Output






Thursday, June 8, 2023

Why python django uploaded images not showing in angular UI profile or any screen ?

Option 1: 

    Note:  keep your images under media/ <folder> for upload and view 


Option 2: 

if you want to change the default media folder under your project root, 

then please go to settings.py 

MEDIA=<custom path> 

MEDIA_URL=<path after above media settings>


Now

http://<url:port>/media/customfolder/image.jpg



Tuesday, June 6, 2023

Ubuntu Port Firewall uwf - not via iptables

 step 1: apt install ufw

step 2: ufw enable

step 3:   sudo nano /etc/default/ufw

          #enable ipv6=yes

step 4: Added default deny of incoming and allow outgoing

   sudo ufw default deny incoming

   sudo ufw default allow outgoing


#. to see the list   

sudo ufw app list


step 5: #. Allow open ssh for all your login and other operations

sudo ufw allow OpenSSH

   sudo ufw allow ssh

   sudo ufw allow 22

   sudo ufw show added

   sudo ufw enable


step 6: #. Allow default web ports and custom ports

   sudo ufw allow http

   sudo ufw allow https

   sudo ufw allow 8099

   sudo ufw allow 88


 

#. To see the port list

   sudo ufw status verbose


#. To deny the ports

   sudo ufw deny <port>


Thank You

https://www.digitalocean.com/community/tutorials/how-to-set-up-a-firewall-with-ufw-on-ubuntu-18-04



Thursday, June 1, 2023

Linux Ubuntu - SSH command to copy server to local or vice versa

 Copy file to Server to Local

    scp -P <port> <localfile path> <server user>@ip:<remote user home path>

    ex: > scp -P 22 mq/target/test.jar drvijay@192.2.2.2:/home/drvijay


Connect server : 

        ssh -p <port> <server user>@<IP>
        ssh -p 22 drvijay@182.2.2.2

Copy file from Server to Local
 





Note: ssh -p <port> small case for port option
          scp -P <port> upper -P for port specify.




Wednesday, May 31, 2023

Ms Sql server problem with linux python django app/settings.py

 From Database {section}


'driver': 'SQL Server Native Client 11.0',


To         

    'driver': 'ODBC Driver 17 for SQL Server'



Hit Counter


View My Stats