Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #urls.py
- from django.urls import path, include
- from . import views
- urlpatterns = [
- path('', views. , name=""),
- ]
- #Media settings for URLs.py
- from django.conf import settings
- from django.conf.urls.static import static
- if settings.DEBUG:
- urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
- #Media and Static settings config
- STATIC_ROOT = os.path.join(BASE_DIR, 'static')
- STATIC_URL = '/static/'
- STATICFILES_DIRS = [
- os.path.join(BASE_DIR, 'somehunt/static/')
- ]
- MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
- MEDIA_URL = '/media/'
- LOGIN_URL = 'login'
- #installed_apps adding -> settings.py
- INSTALLED_APPS = [
- 'blogs.apps.BlogsConfig',
- 'jobs.apps.JobsConfig',
- ]
- #Templates directory adding -> settings.py
- TEMPLATES = [
- {
- 'DIRS': ['tempates'],
- },
- ]
- #Database settings for postgres -> settings.py
- DATABASES = {
- 'default': {
- # 'ENGINE': 'django.db.backends.sqlite3',
- # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
- # 'ENGINE': 'django.db.backends.sqlite3',
- 'ENGINE': 'django.db.backends.postgresql_psycopg2',
- 'NAME': 'producthuntdb',
- 'USER': 'postgres',
- 'PASSWORD': 'testpassword',
- 'HOST': 'localhost',
- 'PORT': '5432'
- }
- }
- # register model
- from django.contrib import admin
- from .models import Product
- # Register your models here.
- admin.site.register(Product)
- #templates
- {% extends 'base.html' %}
- {% block body%}
- {% endblock body %}
- #staticfiles
- {% load staticfiles %}
- # views(basic)
- def home(request):
- return render(request, 'products/home.html')
- # include path
- path('', include('products.urls')),
- # User auth import
- # Auth
- from django.contrib.auth import auth
- auth.login(request, user)
- auth.logout(request)
- # get models from user using key
- from django.contrib.auth.models import User
- user = User.objects.create_user(username=request.POST['username'], password=request.POST['password1'])
- user = User.objects.get(username=request.POST['username'])
- # Model exception
- except User.DoesNotExist
- # Create and save model:
- ModelName.save()
- # if authenticated templates check
- {{ if user.is_authenticated }}
- # logout basehtml code snippit
- {% if user.is_authenticated %}
- <a href="javascript:{document.getElementById('logout').submit()}">Logout</a>
- <form action="{% url 'logout' %}" method="POST" id='logout'>
- {% csrf_token %}
- <input type="hidden">
- </form>
- {% else %}
- <a href="{% url 'login' %}">Login</a>
- {% endif %}
- #commands
- python manage.py runserver
- python manage.py startapp accounts
- python manage.py makemigrations
- python manage.py migrate
- python manage.py createsuperuser
- mkdir templates
- django-admin startproject someproject
- python manage.py collectstatic
- # Register View
- from django.shortcuts import render, redirect
- from django.contrib.auth.models import User
- from django.contrib import auth
- # Create your views here.
- def signup(request):
- if request.method == "POST":
- if request.POST['password1'] == request.POST['password2']:
- try:
- user = User.objects.get(username=request.POST['username'])
- return render(request, 'account/signup.html', {'error': 'Already ase!', 'tag':'danger'})
- except User.DoesNotExist:
- user = User.objects.create_user(username=request.POST['username'], password=request.POST['password1'])
- auth.login(request, user)
- return redirect('home')
- else:
- return render(request, 'account/signup.html', {'error': 'Password ase!', 'tag':'danger'})
- else:
- return render(request, 'account/signup.html')
- #Signup HTML
- from django.shortcuts import render, redirect
- from django.contrib.auth.models import User
- from django.contrib import auth
- # Create your views here.
- def signup(request):
- if request.method == "POST":
- if request.POST['password1'] == request.POST['password2']:
- try:
- user = User.objects.get(username=request.POST['username'])
- return render(request, 'account/signup.html', {'message': 'Already ase!', 'tag':'danger'})
- except User.DoesNotExist:
- user = User.objects.create_user(username=request.POST['username'], password=request.POST['password1'])
- auth.login(request, user)
- return render(request, 'product/home.html', {'message': 'Account Created!', 'tag':'success'})
- else:
- return render(request, 'account/signup.html', {'message': 'Password ase!', 'tag':'danger'})
- else:
- return render(request, 'account/signup.html')
- #LOOOOOOOOOOOOOOOOOOOOGGGGGGGGGGGGGGGIIIIIIINNNNNN VIWEW
- def login(request):
- if request.method == "POST":
- user = auth.authenticate(username=request.POST['username'], password=request.POST['password'])
- if user is not None:
- auth.login(request, user)
- return render(request, 'products/home.html', {'error': user.username})
- else:
- return render(request, 'accounts/login.html', {'error': 'Username or password is incorrect!'})
- else:
- return render(request, 'accounts/login.html')
- #LLLLLLLLLLLLLOOOOOOOOOOOOOOGGGGGGGGGINNNNNNNNNN
- {% extends 'base.html' %}
- {% block content %}
- {% if error %}
- <p>{{error}}</p>
- {% endif %}
- <form class="form" action="{% url 'login' %}" method="POST">
- {% csrf_token %}
- <label for="username">Username</label><br>
- <input type="text" name="username"><br>
- <label for="password">Password</label><br>
- <input type="password" name="password"><br>
- <br>
- <input class="btn btn-primary" type="submit" value="Login">
- </form>
- {% endblock content %}
- #LOGOUT BASE
- <li class="nav-item">
- <a class="nav-link" href="javascript:{document.getElementById('logout').submit()}">Logout</a>
- </li>
- <form id="logout" action="{% url 'logout' %}" method="POST">
- {% csrf_token %}
- <input type="hidden">
- </form>
- #Logout View
- def logout(request):
- if request.method == "POST":
- auth.logout(request)
- return redirect('home')
- #Product Model
- from django.shortcuts import render, redirect, get_object_or_404
- from .models import Product
- from django.utils import timezone
- from django.contrib.auth.decorators import login_required
- # Create your views here.
- def home(request):
- products = Product.objects
- return render(request, 'product/home.html', {'products':products})
- @login_required
- def create(request):
- if request.method == "POST":
- if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.FILES['image'] and request.FILES['icon']:
- product = Product()
- product.title = request.POST['title']
- product.body = request.POST['body']
- product.icon = request.FILES['icon']
- product.image = request.FILES['image']
- product.pub_date = timezone.datetime.now()
- product.hunter = request.user
- if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'):
- product.url = request.POST['url']
- else:
- product.url = 'http://'+request.POST['url']
- product.save()
- return redirect('/product/'+str(product.id))
- else:
- return render(request, 'product/create.html', {"error":"all fields are required!"})
- else:
- return render(request, 'product/create.html')
- #Create Product
- @login_required
- def create(request):
- if request.method == "POST":
- if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.FILES['image'] and request.FILES['icon']:
- product = Product()
- product.title = request.POST['title']
- product.body = request.POST['body']
- product.icon = request.FILES['icon']
- product.image = request.FILES['image']
- product.pub_date = timezone.datetime.now()
- product.hunter = request.user
- if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'):
- product.url = request.POST['url']
- else:
- product.url = 'http://'+request.POST['url']
- product.save()
- return redirect('/product/'+str(product.id))
- else:
- return render(request, 'product/create.html', {"error":"all fields are required!"})
- else:
- return render(request, 'product/create.html')
- #Show detail of the product
- def detail(request, product_id):
- product = get_object_or_404(Product, pk=product_id)
- return render(request, 'product/detail.html', {'product':product})
- #Upvote a product
- @login_required(login_url = 'login')
- def upvote(request, product_id):
- if request.method == "POST":
- product = get_object_or_404(Product, pk=product_id)
- product.votes_total += 1
- product.save()
- return redirect('/products/'+str(product.id))
- else:
- pass
- #Product Detail Page
- {% extends 'base.html' %}
- {% block content %}
- <div class="row">
- <div class="col-2">
- <img src="{{product.icon.url}}" class="img-fluid" >
- </div>
- <div class="col-10">
- <a href="{{product.url}}"><h1>{{product.title}}</h1></a>
- </div>
- </div>
- <div class="row">
- <div class="col-8">
- <img src="{{product.image.url}}" class="img-fluid" alt="" >
- </div>
- <div class="col-4">
- <a href="javascript:{document.getElementById('upvote').submit()}"><button class="btn btn-primary btn-lg btn-block">Upvote {{product.votes_total}}</button></a>
- </div>
- </div>
- <div class="row">
- <div class="col-4">
- <h4>{{product.hunter.username}}</h4>
- </div>
- <div class="col-4 text-right">
- <h4>{{ product.pub_date_pretty }}</h4>
- </div>
- </div>
- <div class="row">
- <div class="col-8">
- <p>{{product.body}}</p>
- </div>
- </div>
- <form id='upvote' action="{% url 'upvote' product.id %}" method="POST">
- {% csrf_token %}
- <input type="hidden">
- </form>
- {% endblock content %}
- #Product URLS
- from django.urls import path, include
- from . import views
- urlpatterns = [
- path('', views.home , name="home"),
- path('create/', views.create, name = 'create'),
- path('<int:product_id>/', views.detail, name = 'detail'),
- path('<int:product_id>/upvote/', views.upvote, name = 'upvote')
- ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement