Skip to content

Instantly share code, notes, and snippets.

@mkushal10
Last active June 16, 2022 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mkushal10/da0c7122abf2a88d3e4ea9b177123091 to your computer and use it in GitHub Desktop.
Save mkushal10/da0c7122abf2a88d3e4ea9b177123091 to your computer and use it in GitHub Desktop.
# To install virtual environment in the system
py -m pip install --user virtualenv
# To check the current version of the virtual environment
py -m pip --version
# for linux
python -m pip --version
# creating the virtual environment
virtualenv -p python3 virtual_environment_name
# for linux
virtualenv --python python3 venv
# activating the virtual environment
virtual_environment_name\Scripts\activate
# for linux
source venv/bin/activate
# installing django framework for the virtual environment
pip install django
# creating a django project
django-admin startproject project_name .
# To run the django server
python manage.py runserver
# Creating a new application inside the project
django-admin startapp app_name
# Move to the settings.py
--->Go to the settings.py file.
# Insert your applictaion name
--->Paste you app name in the INSTALLED_APPS
For Example:
# Example
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app_name',
]
-->Go to the urls.py file of the project_name directory
1. URLS
project_name/urls.py
# Importing views
--> from app_name import views
# add path
--> Add path('', views.function_name),
2. Views
app_name/views.py
# Add below code
from django.http import HttpResponse
def function_name(request):
return HttpResponse("abc")
class TableName(models.Model):
field_name_1 = models.CharField(max_length=255, null=False, blank=False)
field_name_2 = models.TextField()
field_name_3 = models.ForeignKey(ForeignTableName1, on_delete=models.DO_NOTHING)
field_name_4 = models.ForeignKey(ForeignTableName2, on_delete=models.CASCADE, default=1)
field_name_5 = models.TextField(default="")
field_name_6 = models.FileField(upload_to=None, max_length=254)
field_name_7 = models.ImageField(upload_to='folder_name/images', null=True, blank=True, default='image = models.ImageField(upload_to='bev_dish_uploads/images', null=True, blank=True, default='http://www.dar-elweb.com/demos/zarest/assets/img/tableB4.svg')')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
# install Pillow for images and files
pip install Pillow
# Helps to detect the changes to your models
python manage.py makemigartions
# To applying or unapplying as per migrations
python manage.py migrate
# Go to the admins.py file
# Add below lines
from app_name.models import ModelName1, Model2/from app_name.models import *
admin.site.register(ModelName1)
# Create a django user
python manage.py createsuperuser
1. -->Go to the project_name folder add two folders named "static" as well as "media" folders
2. # add os in setting.py file
import os
3. # Add below the STATIC_URL = '/static/'
MEDIA_URL="/media/"
MEDIA_ROOT=os.path.join(BASE_DIR,"media")
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
3. # Go the the static folder
--> Paste all the css, js, images and others folder
4. # Make a folder under templates/app_name
--> paste the html code
5. # Add the below code at the top of the html file
{% load static %}
6. # Add the static
{% static '/folder_name/folder_name/file_name.css' %}
Example:
{% static '/assets/css/style.css' %}
7. # In urls.py
from django.conf.urls.static import static
from django.urls import include
from project_name import settings
urlpatterns = [
path()
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
-->Go to the project_name folder add a new folder named "templates" folder
--> Go to the setting.py file
Check the import os
TEMPLATES = [
{
# add this
'DIRS': [os.path.join(BASE_DIR, 'templates')],
}
# Add a folder inline of main project folder as templates
# create another folder named app_name under templates folder
# create html_file_name.html inside the app_name folder
-->Go to the urls.py file of the project_name directory
1. URLS
project_name/urls.py
# Importing views
--> from app_name import views
# add path
--> Add path('', views.function_name),
# defing function
def function_name(request):
# return type
# render takes parameters
return render(request, "app_name/html_file_name.html")
1. --> Go to the views.py in the app_name folder
from .models import *
def function_name(request):
conxtext_name = ModelName.objects.all()
return render(request, "app_name/html_file_name.html", {'conxtext_name':conxtext_name})
---------------OR------------------------------
def function_name(request):
context_name = ModelName.objects.all()
context_name = ModelName.objects.all()
context = {'context_name':context_name, 'context_name':context_name}
return render(request, 'app_name/html_file_name.html', context)
2. --> Go to the html_file.html
#add below code
{% for i in conxtext_name %}
<tr>
<td>{{i.field_name1}}</td>
<td>{{i.field_name2}}</td>
<td>{{i.image_field.url}}</td> #Display image field
</tr>
{% endfor %}
# Go to the html_file_name.html
# Add below code
{% for item in items %}
<tr>
<td>{{ forloop.counter }}</td>
</tr>
Three Types: a. Integer b. String c. Slug
1. urls.py
from django.contrib import admin
from django.urls import path
from project_name import views
urlpatterns = [
path('course/', views.course),
path('course/<int:courseid>', views.courseDetails), #Integer
path('courses/<str:courseid>', views.courseDetails), #String
path('coursess/<slug:courseid>', views.courseDetails), #Slug
path('coursess/<courseid>', views.courseDetails), #All Types
]
2. views.py
def courseDetails(request, courseid):
return HttpResponse(courseid)
# Go to the settings.py file
# Set as below code
TIME_ZONE = 'Asia/Kathmandu'
Go to the SETTING.py
Add below code in the MIDDLEWARE
--> 'django.middleware.locale.LocaleMiddleware'
Add below code in the Internationalization
LANGUAGES = [
('en', _('English')),
('ne', _('Nepali')),
]
#LANGUAGE_CODE = 'en-us'
import os
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
Installation
--> pip install python-gettext
# Add in models
from hotel_restro.utils import unique_slug_generator
from django.db.models.signals import pre_save
class ModelName(models.Model):
slug = models.SlugField(max_length=255, null=True, blank=True)
def slug_generator(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug=unique_slug_generator(instance)
pre_save.connect(slug_generator, sender=ModelName)
# Make a utils.py file inside the project folder (Hints: At the same line of settings.py file)
import random
import string
from django.utils.text import slugify
def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def unique_slug_generator(instance, new_slug=None):
"""
This is for a Django project and it assumes your instance
has a model with a slug field and a title character (char) field.
"""
if new_slug is not None:
slug = new_slug
else:
slug = slugify(instance.title)
Klass = instance.__class__
qs_exists = Klass.objects.filter(slug=slug).exists()
if qs_exists:
new_slug = "{slug}-{randstr}".format(
slug=slug,
randstr=random_string_generator(size=4)
)
return unique_slug_generator(instance, new_slug=new_slug)
return slug
# urls.py
path('path/<slug:slug_text>', views.function_name),
# views.py file
def function_name(request):
context_name = ModelName.objects.all()
return render(request, 'app_name/html_file_name.html', {'context_name': context_name})
def table_details(request, slug_text):
query = ModelName.objects.filter(slug=slug_text)
if query.exists():
query = query.first()
else:
# return HttpResponse('bac');
return render(request, 'app_name/html_file_name.html')
context_name = ModelName.objects.all()
# return HttpResponse('bac');
return render(request, 'restro_app/html_file_name.html', {'context_name': context_name})
# In html file
<a href="/app_name/{{ i.slug }}" class="btn btn-secondary" role="button" data-bs-toggle="button">Details</a>
asgiref==3.5.1
certifi==2021.10.8
cffi==1.15.0
charset-normalizer==2.0.12
coreapi==2.3.3
coreschema==0.0.4
cryptography==37.0.2
defusedxml==0.7.1
Django==4.0.4
django-allauth==0.51.0
django-ckeditor==6.4.1
django-cors-headers==3.12.0
django-countries==7.3.2
django-crispy-forms==1.14.0
django-debug-toolbar==3.4.0
django-filter==21.1
django-js-asset==2.0.0
django-templated-mail==1.1.1
djangorestframework==3.13.1
djangorestframework-simplejwt==4.8.0
djoser==2.1.0
drf-yasg==1.20.0
idna==3.3
inflection==0.5.1
itypes==1.2.0
Jinja2==3.1.2
MarkupSafe==2.1.1
oauthlib==3.2.0
packaging==21.3
Pillow==9.1.0
psycopg2-binary==2.9.3
pycparser==2.21
PyJWT==2.4.0
pyparsing==3.0.9
python-decouple==3.6
python3-openid==3.2.0
pytz==2022.1
requests==2.27.1
requests-oauthlib==1.3.1
ruamel.yaml==0.17.21
ruamel.yaml.clib==0.2.6
six==1.16.0
social-auth-app-django==4.0.0
social-auth-core==4.2.0
sqlparse==0.4.2
typing_extensions==4.2.0
uritemplate==4.1.1
urllib3==1.26.9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment