Commit 48a4db05 authored by aurellesia's avatar aurellesia

first commit

parents
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="PLAIN" />
<option name="myDocStringFormat" value="Plain" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="PROJECT_PROFILE" value="Default" />
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Pipenv (firstTry)" project-jdk-type="Python SDK" />
<component name="PyCharmProfessionalAdvertiser">
<option name="shown" value="true" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/firstTry.iml" filepath="$PROJECT_DIR$/.idea/firstTry.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
[[source]]
url = "https://pypi.python.org/simple"
verify_ssl = true
name = "pypi"
[packages]
django = "*"
mysqlclient = "*"
[dev-packages]
[requires]
python_version = "3.8"
{
"_meta": {
"hash": {
"sha256": "e984640bdb97faeca5aa1c2c3454f0469cf16255974870261ad9fa529d2c9b8f"
},
"pipfile-spec": 6,
"requires": {
"python_version": "3.8"
},
"sources": [
{
"name": "pypi",
"url": "https://pypi.python.org/simple",
"verify_ssl": true
}
]
},
"default": {
"asgiref": {
"hashes": [
"sha256:2f8abc20f7248433085eda803936d98992f1343ddb022065779f37c5da0181d0",
"sha256:88d59c13d634dcffe0510be048210188edd79aeccb6a6c9028cdad6f31d730a9"
],
"version": "==3.5.0"
},
"backports.zoneinfo": {
"hashes": [
"sha256:17746bd546106fa389c51dbea67c8b7c8f0d14b5526a579ca6ccf5ed72c526cf",
"sha256:1b13e654a55cd45672cb54ed12148cd33628f672548f373963b0bff67b217328",
"sha256:1c5742112073a563c81f786e77514969acb58649bcdf6cdf0b4ed31a348d4546",
"sha256:4a0f800587060bf8880f954dbef70de6c11bbe59c673c3d818921f042f9954a6",
"sha256:5c144945a7752ca544b4b78c8c41544cdfaf9786f25fe5ffb10e838e19a27570",
"sha256:7b0a64cda4145548fed9efc10322770f929b944ce5cee6c0dfe0c87bf4c0c8c9",
"sha256:8439c030a11780786a2002261569bdf362264f605dfa4d65090b64b05c9f79a7",
"sha256:8961c0f32cd0336fb8e8ead11a1f8cd99ec07145ec2931122faaac1c8f7fd987",
"sha256:89a48c0d158a3cc3f654da4c2de1ceba85263fafb861b98b59040a5086259722",
"sha256:a76b38c52400b762e48131494ba26be363491ac4f9a04c1b7e92483d169f6582",
"sha256:da6013fd84a690242c310d77ddb8441a559e9cb3d3d59ebac9aca1a57b2e18bc",
"sha256:e55b384612d93be96506932a786bbcde5a2db7a9e6a4bb4bffe8b733f5b9036b",
"sha256:e81b76cace8eda1fca50e345242ba977f9be6ae3945af8d46326d776b4cf78d1",
"sha256:e8236383a20872c0cdf5a62b554b27538db7fa1bbec52429d8d106effbaeca08",
"sha256:f04e857b59d9d1ccc39ce2da1021d196e47234873820cbeaad210724b1ee28ac",
"sha256:fadbfe37f74051d024037f223b8e001611eac868b5c5b06144ef4d8b799862f2"
],
"markers": "python_version < '3.9'",
"version": "==0.2.1"
},
"django": {
"hashes": [
"sha256:2485eea3cc4c3bae13080dee866ebf90ba9f98d1afe8fda89bfb0eb2e218ef86",
"sha256:7cd8e8a3ed2bc0dfda05ce1e53a9c81b30eefd7aa350e538a18884475e4d4ce2"
],
"index": "pypi",
"version": "==4.0.1"
},
"mysqlclient": {
"hashes": [
"sha256:02c8826e6add9b20f4cb12dcf016485f7b1d6e30356a1204d05431867a1b3947",
"sha256:2c8410f54492a3d2488a6a53e2d85b7e016751a1e7d116e7aea9c763f59f5e8c",
"sha256:973235686f1b720536d417bf0a0d39b4ab3d5086b2b6ad5e6752393428c02b12",
"sha256:b62d23c11c516cedb887377c8807628c1c65d57593b57853186a6ee18b0c6a5b",
"sha256:e6279263d5a9feca3e0edbc2b2a52c057375bf301d47da2089c075ff76331d14"
],
"index": "pypi",
"version": "==2.1.0"
},
"sqlparse": {
"hashes": [
"sha256:0c00730c74263a94e5a9919ade150dfc3b19c574389985446148402998287dae",
"sha256:48719e356bb8b42991bdbb1e8b83223757b93789c00910a616a071910ca4a64d"
],
"version": "==0.4.2"
}
},
"develop": {}
}
"""
ASGI config for firstTry project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'firstTry.settings')
application = get_asgi_application()
"""
Django settings for firstTry project.
Generated by 'django-admin startproject' using Django 4.0.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-nb)*j5x7fpys5erz%bc7p#pr%zqp$wf(a#_$nt2^f73^5koj&h'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'prodcat.apps.ProdcatConfig',
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'firstTry.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'firstTry.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '127.0.0.1',
'USER': 'root',
'PASSWORD': 'root123',
'NAME': 'firstTry',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
'charset': 'utf8mb4',
},
},
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
"""firstTry URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('products/', include('prodcat.urls')),
path('admin/', admin.site.urls),
]
"""
WSGI config for firstTry project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'firstTry.settings')
application = get_wsgi_application()
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'firstTry.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
from django.contrib import admin
# Register your models here.
from .models import Question, Choice
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes':['collapse']}),
]
inlines = [ChoiceInline]
list_display = ('question_text', 'pub_date', 'was_published_recently')
list_filter = ['pub_date']
search_fields = ['question_text']
admin.site.register(Question, QuestionAdmin)
from django.apps import AppConfig
class PollsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'polls'
# Generated by Django 4.0.1 on 2022-01-25 07:48
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Question',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('question_text', models.CharField(max_length=200)),
('pub_date', models.DateTimeField(verbose_name='date published')),
],
),
migrations.CreateModel(
name='Choice',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('choice_text', models.CharField(max_length=200)),
('votes', models.IntegerField(default=0)),
('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.question')),
],
),
]
import datetime
from django.db import models
from django.utils import timezone
from django.contrib import admin
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
@admin.display(
boolean=True,
ordering='pub_date',
description='Published Recently?',
)
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
li a {
color: blue;
}
\ No newline at end of file
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
<fieldset>
<legend><h1>{{ question.question_text }}</h1></legend>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
</fieldset>
<input type="submit" value="Vote">
</form>
\ No newline at end of file
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>
<a href="{% url 'polls:detail' question.id %}">{{question.question_text}}</a>
</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}">
\ No newline at end of file
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>
<a href="{% url 'polls:detail' question.id %}">Vote again?</a>
\ No newline at end of file
from django.test import TestCase
# Create your tests here.
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
\ No newline at end of file
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.views import generic #import generic view
from .models import Question, Choice
class IndexView(generic.ListView): #ListView to display list of object
template_name = 'polls/index.html' #template that display list
context_object_name = 'latest_question_list' #object name that used by the view
def get_queryset(self): #get list of object item
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id) #get the question
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
\ No newline at end of file
from django.contrib import admin
# Register your models here.
from django.apps import AppConfig
class ProdcatConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'prodcat'
from django import forms
from .models import Category, Products
class CategoryForm(forms.ModelForm):
class Meta:
model=Category
fields="__all__"
error_messages = {
'category_text' : {
'required':'Category text cannot be empty'
}
}
class ProductForm(forms.ModelForm):
class Meta:
model=Products
fields="__all__"
error_messages = {
'name' : {
'required':'Name cannot be empty'
},
'price' : {
'required' :'Price cannot be empty'
},
'restock_date':{
'required' : 'Restock date cannot be empty'
},
'category':{
'required' : 'Category cannot be empty'
}
}
\ No newline at end of file
# Generated by Django 4.0.1 on 2022-01-26 02:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('category_text', models.CharField(max_length=200)),
],
),
migrations.CreateModel(
name='Products',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200)),
('price', models.IntegerField()),
('restock_date', models.DateTimeField(verbose_name='date restock')),
('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='prodcat.category')),
],
),
]
from django.db import models
# Create your models here.
class Category(models.Model):
category_text=models.CharField(max_length=200)
def __str__(self):
return self.category_text
class Products(models.Model):
name=models.CharField(max_length=200)
price=models.IntegerField(blank=False, null=False)
restock_date=models.DateTimeField('date restock')
category=models.ForeignKey(Category, on_delete=models.CASCADE)
def __str__(self):
return self.name
<div>
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div>
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div >
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
<form method="post">
{% csrf_token %}
<table style="margin:20px auto;">
<tr>
<td>Category Name</td>
<td>
<input type="text" name="category_text" value=""></td>
</tr>
<td></td>
<td><input type="button" onclick = "window.history.back()" value="Back"></td>
<td><input type="submit" value="Save"></td>
</table>
</form>
</div>
\ No newline at end of file
<h1>Table Category</h1>
<br/>
<div>
<a href="/products/">Back</a><br>
<a href="add-category/">Add new category</a>
<table>
<thead>
<tr>
<th>Category Name</th>
</tr>
</thead>
<tbody>
{% for item in data %}
<tr>
<td>{{item.category_text}}</td>
<td>
<a type="button" href="delete-category/{{item.id}}" onclick="return confirm('Are you sure to delete this category ?');">Delete</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
\ No newline at end of file
<div>
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div>
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div >
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
<form method="post">
{% csrf_token %}
<table style="margin:20px auto;">
<tr>
<td>Name</td>
<td>
<input type="text" name="name" value=""></td>
</tr>
<tr>
<td>Price</td>
<td>
<input type="number" name="price" value=""></td>
</tr>
<tr>
<td>Restock Date</td>
<td>
<input type="date" name="restock_date" value=""></td>
</tr>
<tr>
<td>Category</td>
<td>
<select name="category">
{% for item in category %}
<option value="{{item.id}}">{{ item.category_text }}</option>
{% endfor %}
</select>
</tr>
<td></td>
<td><a type="button" href = "/products/">Back</a></td>
<td><input type="submit" value="Save"></td>
</tr>
</table>
</form>
</div>
\ No newline at end of file
<h1>Table Products</h1>
<br/>
<div>
<a href="cat/">Check Categories</a> <br>
<a href="add-product/">Add new product</a>
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Stock Date</th>
<th>Category</th>
</tr>
</thead>
<tbody>
{% for item in data %}
<tr>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>{{item.restock_date}}</td>
<td>{{item.category_id}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
\ No newline at end of file
from django.test import TestCase
# Create your tests here.
from django.urls import path
from . import views
app_name='prodcat'
urlpatterns = [
path('', views.productIndex, name='productIndex'),
path('cat/', views.categoryIndex, name='categoryIndex'),
path('add-product/', views.storeProduct, name='storeProduct'),
path('cat/add-category/', views.storeCategory, name='storeCategory'),
path('cat/delete-category/<int:id>', views.destroyCategory)
]
\ No newline at end of file
from django.shortcuts import render, redirect
from .models import Products, Category
from .forms import CategoryForm, ProductForm
# Create your views here.
def categoryIndex(request):
result=Category.objects.all()
context={
'data':result,
}
return render(request,'prodcat/categoryIndex.html',context)
def destroyCategory(request, id):
data = Category.objects.get(id=id)
data.delete()
return redirect('/products/cat')
def storeCategory(request):
form = CategoryForm(request.POST or None, request.FILES or None)
if request.method == 'POST':
if form.is_valid():
form.save()
return redirect('/products/cat')
pass
return render(request, 'prodcat/categoryAdd.html', {'form' : form})
def productIndex(request):
result=Products.objects.all()
context={
'data':result,
}
return render(request,'prodcat/productIndex.html',context)
def storeProduct(request):
form = ProductForm(request.POST or None, request.FILES or None)
if request.method == 'POST':
if form.is_valid():
print(form)
form.save()
return redirect('/products/')
pass
cat = Category.objects.all()
context={
'category' : cat,
'form' : form
}
return render(request, 'prodcat/productAdd.html', context)
\ No newline at end of file
{% extends "admin/base.html" %}
{% block title %}{% if subtitle %}{{ subtitle }} | {% endif %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}
{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">Polls Admin</a></h1>
{% endblock %}
{% block nav-global %}{% endblock %}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment