Advertisement
arfin97

Django Reference Sheet

May 28th, 2019
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.50 KB | None | 0 0
  1. #urls.py
  2. from django.urls import path, include
  3. from . import views
  4.  
  5. urlpatterns = [
  6.     path('', views. , name=""),
  7. ]
  8.  
  9. #Media settings for URLs.py
  10. from django.conf import settings
  11. from django.conf.urls.static import static
  12.  
  13. if settings.DEBUG:
  14.     urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  15.  
  16. #Media and Static settings config
  17.  
  18. STATIC_ROOT = os.path.join(BASE_DIR, 'static')
  19. STATIC_URL = '/static/'
  20. STATICFILES_DIRS = [
  21.     os.path.join(BASE_DIR, 'somehunt/static/')
  22. ]
  23.  
  24. MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
  25. MEDIA_URL = '/media/'
  26.  
  27. LOGIN_URL = 'login'
  28.  
  29.  
  30. #installed_apps adding -> settings.py
  31. INSTALLED_APPS = [
  32.     'blogs.apps.BlogsConfig',
  33.     'jobs.apps.JobsConfig',
  34. ]
  35.  
  36. #Templates directory adding -> settings.py
  37. TEMPLATES = [
  38.     {
  39.         'DIRS': ['tempates'],
  40.     },
  41. ]
  42.  
  43. #Database settings for postgres -> settings.py
  44. DATABASES = {
  45.     'default': {
  46.         # 'ENGINE': 'django.db.backends.sqlite3',
  47.         # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
  48.         # 'ENGINE': 'django.db.backends.sqlite3',
  49.         'ENGINE': 'django.db.backends.postgresql_psycopg2',
  50.         'NAME': 'producthuntdb',
  51.         'USER': 'postgres',
  52.         'PASSWORD': 'testpassword',
  53.         'HOST': 'localhost',
  54.         'PORT': '5432'
  55.     }
  56. }
  57.  
  58.  
  59. # register model
  60. from django.contrib import admin
  61. from .models import Product
  62. # Register your models here.
  63. admin.site.register(Product)
  64.  
  65. #templates
  66. {% extends 'base.html' %}
  67.  
  68. {% block body%}
  69.  
  70. {% endblock body %}
  71.  
  72. #staticfiles
  73. {% load staticfiles %}
  74.  
  75. # views(basic)
  76. def home(request):
  77.     return render(request, 'products/home.html')
  78. # include path
  79. path('', include('products.urls')),
  80.  
  81. # User auth import
  82.  
  83. # Auth
  84. from django.contrib.auth import auth
  85. auth.login(request, user)
  86. auth.logout(request)
  87. # get models from user using key
  88. from django.contrib.auth.models import User
  89. user = User.objects.create_user(username=request.POST['username'], password=request.POST['password1'])
  90. user = User.objects.get(username=request.POST['username'])
  91.  
  92. # Model exception
  93. except User.DoesNotExist
  94.  
  95. # Create and save model:
  96. ModelName.save()
  97.  
  98. # if authenticated templates check
  99. {{ if user.is_authenticated }}
  100.  
  101.  
  102.  
  103. # logout basehtml code snippit
  104. {% if user.is_authenticated %}
  105.     <a href="javascript:{document.getElementById('logout').submit()}">Logout</a>
  106.     <form action="{% url 'logout' %}" method="POST" id='logout'>
  107.         {% csrf_token %}
  108.         <input type="hidden">
  109.     </form>
  110.     {% else %}
  111.         <a href="{% url 'login' %}">Login</a>
  112. {% endif %}
  113.  
  114.  
  115.  
  116.  
  117.  
  118.  
  119. #commands
  120. python manage.py runserver
  121. python manage.py startapp accounts
  122. python manage.py makemigrations
  123. python manage.py migrate
  124. python manage.py createsuperuser
  125.  
  126. mkdir templates
  127. django-admin startproject someproject
  128. python manage.py collectstatic
  129.  
  130.  
  131.  
  132.  
  133.  
  134.  
  135. # Register View
  136. from django.shortcuts import render, redirect
  137. from django.contrib.auth.models import User
  138. from django.contrib import auth
  139. # Create your views here.
  140.  
  141. def signup(request):
  142.     if request.method == "POST":
  143.         if request.POST['password1'] == request.POST['password2']:
  144.             try:
  145.                 user = User.objects.get(username=request.POST['username'])
  146.                 return render(request, 'account/signup.html', {'error': 'Already ase!', 'tag':'danger'})
  147.             except User.DoesNotExist:
  148.                 user = User.objects.create_user(username=request.POST['username'], password=request.POST['password1'])
  149.                 auth.login(request, user)
  150.                 return redirect('home')
  151.         else:
  152.             return render(request, 'account/signup.html', {'error': 'Password ase!', 'tag':'danger'})
  153.  
  154.     else:
  155.         return render(request, 'account/signup.html')
  156.  
  157.  
  158. #Signup HTML
  159. from django.shortcuts import render, redirect
  160. from django.contrib.auth.models import User
  161. from django.contrib import auth
  162. # Create your views here.
  163.  
  164. def signup(request):
  165.     if request.method == "POST":
  166.         if request.POST['password1'] == request.POST['password2']:
  167.             try:
  168.                 user = User.objects.get(username=request.POST['username'])
  169.                 return render(request, 'account/signup.html', {'message': 'Already ase!', 'tag':'danger'})
  170.             except User.DoesNotExist:
  171.                 user = User.objects.create_user(username=request.POST['username'], password=request.POST['password1'])
  172.                 auth.login(request, user)
  173.                 return render(request, 'product/home.html', {'message': 'Account Created!', 'tag':'success'})
  174.         else:
  175.             return render(request, 'account/signup.html', {'message': 'Password ase!', 'tag':'danger'})
  176.  
  177.     else:
  178.         return render(request, 'account/signup.html')
  179.  
  180.  
  181. #LOOOOOOOOOOOOOOOOOOOOGGGGGGGGGGGGGGGIIIIIIINNNNNN VIWEW
  182. def login(request):
  183.     if request.method == "POST":
  184.         user = auth.authenticate(username=request.POST['username'], password=request.POST['password'])
  185.         if user is not None:
  186.             auth.login(request, user)
  187.             return render(request, 'products/home.html', {'error': user.username})
  188.         else:
  189.             return render(request, 'accounts/login.html', {'error': 'Username or password is incorrect!'})
  190.     else:
  191.         return render(request, 'accounts/login.html')
  192.  
  193.  
  194.  
  195. #LLLLLLLLLLLLLOOOOOOOOOOOOOOGGGGGGGGGINNNNNNNNNN
  196. {% extends 'base.html' %}
  197.  
  198. {% block content %}
  199. {% if error %}
  200.     <p>{{error}}</p>
  201. {% endif %}
  202.  
  203. <form class="form" action="{% url 'login' %}" method="POST">
  204.     {% csrf_token %}
  205.     <label for="username">Username</label><br>
  206.     <input type="text" name="username"><br>
  207.     <label for="password">Password</label><br>
  208.     <input type="password" name="password"><br>
  209.     <br>
  210.     <input class="btn btn-primary" type="submit" value="Login">
  211. </form>
  212. {% endblock content %}
  213.  
  214.  
  215.  
  216.  
  217.  
  218. #LOGOUT BASE
  219.  <li class="nav-item">
  220.     <a class="nav-link" href="javascript:{document.getElementById('logout').submit()}">Logout</a>
  221.   </li>
  222.   <form id="logout" action="{% url 'logout' %}" method="POST">
  223.     {% csrf_token %}
  224.     <input type="hidden">
  225.   </form>
  226.  
  227.  
  228. #Logout View
  229. def logout(request):
  230.     if request.method == "POST":
  231.         auth.logout(request)
  232.         return redirect('home')
  233.  
  234.  
  235.  
  236. #Product Model
  237.  
  238. from django.shortcuts import render, redirect, get_object_or_404
  239. from .models import Product
  240. from django.utils import timezone
  241. from django.contrib.auth.decorators import login_required
  242. # Create your views here.
  243. def home(request):
  244.     products = Product.objects
  245.     return render(request, 'product/home.html', {'products':products})
  246.  
  247. @login_required
  248. def create(request):
  249.     if request.method == "POST":
  250.         if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.FILES['image'] and request.FILES['icon']:
  251.             product = Product()
  252.             product.title = request.POST['title']
  253.             product.body = request.POST['body']
  254.             product.icon = request.FILES['icon']
  255.             product.image = request.FILES['image']
  256.             product.pub_date = timezone.datetime.now()
  257.             product.hunter = request.user
  258.             if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'):
  259.                 product.url = request.POST['url']
  260.             else:
  261.                 product.url = 'http://'+request.POST['url']
  262.  
  263.             product.save()
  264.  
  265.             return redirect('/product/'+str(product.id))
  266.         else:
  267.             return render(request, 'product/create.html', {"error":"all fields are required!"})
  268.  
  269.     else:
  270.         return render(request, 'product/create.html')
  271.  
  272.  
  273. #Create Product
  274. @login_required
  275. def create(request):
  276.     if request.method == "POST":
  277.         if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.FILES['image'] and request.FILES['icon']:
  278.             product = Product()
  279.             product.title = request.POST['title']
  280.             product.body = request.POST['body']
  281.             product.icon = request.FILES['icon']
  282.             product.image = request.FILES['image']
  283.             product.pub_date = timezone.datetime.now()
  284.             product.hunter = request.user
  285.             if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'):
  286.                 product.url = request.POST['url']
  287.             else:
  288.                 product.url = 'http://'+request.POST['url']
  289.  
  290.             product.save()
  291.  
  292.             return redirect('/product/'+str(product.id))
  293.         else:
  294.             return render(request, 'product/create.html', {"error":"all fields are required!"})
  295.  
  296.     else:
  297.         return render(request, 'product/create.html')
  298.  
  299. #Show detail of the product
  300. def detail(request, product_id):
  301.     product = get_object_or_404(Product, pk=product_id)
  302.     return render(request, 'product/detail.html', {'product':product})
  303.  
  304. #Upvote a product
  305. @login_required(login_url = 'login')
  306. def upvote(request, product_id):
  307.     if request.method == "POST":
  308.         product = get_object_or_404(Product, pk=product_id)
  309.         product.votes_total += 1
  310.         product.save()
  311.         return redirect('/products/'+str(product.id))
  312.     else:
  313.         pass
  314.  
  315. #Product Detail Page
  316. {% extends 'base.html' %}
  317.  
  318. {% block content %}
  319. <div class="row">
  320.     <div class="col-2">
  321.         <img src="{{product.icon.url}}" class="img-fluid" >
  322.     </div>
  323.     <div class="col-10">
  324.         <a href="{{product.url}}"><h1>{{product.title}}</h1></a>
  325.     </div>
  326.  
  327. </div>
  328.  
  329. <div class="row">
  330.     <div class="col-8">
  331.         <img src="{{product.image.url}}" class="img-fluid" alt="" >
  332.     </div>
  333.     <div class="col-4">
  334.         <a href="javascript:{document.getElementById('upvote').submit()}"><button  class="btn btn-primary btn-lg btn-block">Upvote {{product.votes_total}}</button></a>
  335.     </div>
  336. </div>
  337.  
  338. <div class="row">
  339.     <div class="col-4">
  340.         <h4>{{product.hunter.username}}</h4>
  341.     </div>
  342.     <div class="col-4 text-right">
  343.         <h4>{{ product.pub_date_pretty }}</h4>
  344.     </div>
  345. </div>
  346.  
  347. <div class="row">
  348.     <div class="col-8">
  349.         <p>{{product.body}}</p>
  350.     </div>
  351. </div>
  352.  
  353.  
  354. <form id='upvote' action="{% url 'upvote' product.id %}" method="POST">
  355.     {% csrf_token %}
  356.     <input type="hidden">
  357. </form>
  358. {% endblock content %}
  359.  
  360.  
  361. #Product URLS
  362. from django.urls import path, include
  363. from . import views
  364.  
  365. urlpatterns = [
  366.     path('', views.home , name="home"),
  367.  
  368.     path('create/', views.create, name = 'create'),
  369.     path('<int:product_id>/', views.detail, name = 'detail'),
  370.     path('<int:product_id>/upvote/', views.upvote, name = 'upvote')
  371.  
  372. ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement