Skip to content

Instantly share code, notes, and snippets.

@wolfsyntax
Last active June 26, 2019 05:33
Show Gist options
  • Save wolfsyntax/c9c0fa94663c48b86c4f611b7ce7372a to your computer and use it in GitHub Desktop.
Save wolfsyntax/c9c0fa94663c48b86c4f611b7ce7372a to your computer and use it in GitHub Desktop.
Django Framework
#views.py
stats = '-'
if request.method == 'POST':
form = GoatInfoForm(request.POST) #{}
if form.is_valid():
cd = form.cleaned_data #outpur: dictionary
form_clean = GoatInfoForm(cd)
#cd.save()
stats = 'save'
#form_clean.save()
if cd['category'] == 'birth':
birth_info = {
'dam': request.POST['dam_id'],
'sire': request.POST['sire_id'],
'eartag': cd['eartag_id']
}
birthInfo_form = BirthInfoForm(birth_info)
birth_stat = 'not valid'
if birthInfo_form.is_valid():
birth_stat = 'valid'
cdb = birthInfo_form.cleaned_data
cdb.save()
return HttpResponse("{} is categorized as By Birth is {}".format(cd['eartag_id'],birth_stat))
else:
purchase_info = {
'purchase_date': request.POST['purchase_date'],
'purchase_weight': request.POST['purchase_weight'],
'purchase_price': request.POST['purchase_price'],
'purchase_from': request.POST['purchase_from']
}
return HttpResponse("{} is categorized as By Purchase".format(cd['eartag_id']))
#endif
else:
return HttpResponse("Form Data is not valid")
#endif
else:
form = GoatInfoForm()
#endif
context = {
'title': 'Django: the Web framework for perfectionists with deadlines. %s'%stats,
'form': form
}
return render(request, 'index.html', context)
#models.py
class Profile(models.Model):
GENDER = (
('', '-- Please Select --'),
('female','Female'),
('male', 'Male'),
)
STATUS = (
('', '-- Please Select --'),
('active', 'Active'),
('sold', 'Sold'),
('deceased', 'Deceased'),
('lost', 'Lost'),
('stolen', ' Stolen'),
)
CATEGORY = (
('purchase', 'By Purchase'),
('birth', 'By Birth'),
)
eartag_id = models.IntegerField(primary_key=True)
eartag_color = models.CharField(max_length=250, choices=((None, '-- Choose color --'), ('blue', 'Blue'), ('green', 'Green'), ('orange', 'Orange'), ('yellow','Yellow')))
body_color = models.CharField(max_length=64)
gender = models.CharField(max_length=10,choices=GENDER)
nickname = models.CharField(max_length=250)
is_castrated = models.BooleanField()
status = models.CharField(max_length=32, choices=STATUS, default='active')
category = models.CharField(max_length=32,choices=CATEGORY)
birth_date = models.DateField()
class Meta:
ordering = ('eartag_id',)
get_latest_by = 'birth_date'
db_table = 'goat_profile'
class Birth_record(models.Model):
birth_id = models.AutoField(primary_key=True)
dam = models.ForeignKey(Profile, related_name='dam_profile', on_delete=models.CASCADE)
sire = models.ForeignKey(Profile, related_name='sire_profile', on_delete=models.CASCADE)
eartag = models.ForeignKey(Profile, related_name='offspring_profile', on_delete=models.CASCADE)
class Meta:
ordering = ('birth_id','eartag_id',)
db_table = 'birth_record'
get_latest_by = 'birth_id'
def __str__(self):
return "%d is the offspring of %d (dam) and %d (sire)"%(self.eartag_id, self.dam_id, self.sire_id)
class Purchase_record(models.Model):
purchase_id = models.AutoField(primary_key=True)
purchase_weight = models.DecimalField(decimal_places=2, max_digits=11)
purchase_price = models.FloatField()
purchase_date = models.DateField(auto_now=True)
purchase_from = models.CharField(max_length=250)
eartag = models.ForeignKey(Profile, on_delete=models.CASCADE)
user = models.ForeignKey(User, related_name='goat_purchase', on_delete=models.CASCADE)
class Meta:
ordering = ('purchase_id','purchase_date','eartag_id',)
db_table = 'purchase_record'
get_latest_by = 'purchase_date'
#forms.py
from django import forms
from .models import Profile, Purchase_record, Birth_record
#class GoatInfoForm(forms.Form):
class GoatInfoForm(forms.ModelForm):
# eartag_id = forms.IntegerField(min_value=1,widget=forms.widgets.NumberInput(attrs={'class': 'form-control', 'id': 'eartag_id'}))
# eartag_color = forms.ChoiceField(choices=((None, '-- Choose color --'), ('blue', 'Blue'), ('green', 'Green'), ('orange', 'Orange'), ('yellow','Yellow')), widget=forms.widgets.Select(attrs={'class': 'form-control', 'id': 'eartag_color'}))
# nickname = forms.RegexField(regex='^[a-zA-Z ]{4,}$', widget=forms.widgets.TextInput(attrs={'class': 'form-control', 'id': 'nickname'}))
# gender = forms.ChoiceField(choices=(('', '-- Please Select --'), ('male', 'Male'), ('female', 'Female'), ), widget=forms.widgets.Select(attrs={'class': 'form-control', 'id': 'gender'}))
#body_color = forms.CharField(widget=forms.widgets.TextInput(attrs={'class': 'form-control', 'id': 'body_color'}))
# body_color = forms.RegexField(regex='^[a-zA-Z ]{3,}$', widget=forms.widgets.TextInput(attrs={'class': 'form-control', 'id': 'body_color'}))
# category = forms.ChoiceField(choices=(('birth', 'By Birth'), ('purchase', 'By Purchase')), widget=forms.widgets.Select(attrs={'class': 'form-control', 'id': 'category'}))
# is_castrated = forms.BooleanField(required=False, widget=forms.widgets.CheckboxInput(attrs={'class': '', 'id': 'is_castrated'}))
#def cleaned_data(self):
# super(GoatInfoForm, self).clean()
# eartag_id = self.cleaned_data.get('eartag_id', '')
# print("\n\n\nEartag ID: %d\n\n\n\n\n"% eartag_id)
# eartag_color = self.cleaned_data.get('eartag_color', '')
# nickname = self.cleaned_data.get('nickname', '')
# gender = self.cleaned_data.get('gender', '')
# body_color = self.cleaned_data.get('body_color', '')
# category = self.cleaned_data.get('category', '')
# is_castrated = self.cleaned_data.get('is_castrated', '')
#return {'eartag_id': eartag_id}
class Meta:
model = Profile
fields = ('eartag_id','eartag_color','nickname','gender','body_color','birth_date','category','is_castrated',)#'__all__'
#labels = {'eartag_id': 'Eartag ID'}
#widgets = {
# 'eartag_id': forms.widgets.NumberInput(attrs={'class':'form-control', 'id': 'eartag_id'}),
# 'eartag_color': forms.widgets.Select(attrs={'class':'form-control', 'id': 'eartag_color'}),
# 'gender': forms.widgets.Select(attrs={'class':'form-control', 'id': 'gender'}),
# 'nickname': forms.widgets.TextInput(attrs={'class':'form-control','id':'nickname'}),
# 'birth_date': forms.widgets.DateTimeInput(attrs={'class':'form-control', 'id':'birth_date'}),
#}
class PurchaseInfoForm(forms.ModelForm):
class Meta:
model = Purchase_record
fields = '__all__'
class BirthInfoForm(forms.ModelForm):
def cleaned_data(self):
super(BirthInfoForm, self).clean()
eartag = self.cleaned_data.get('eartag_id', '')
print("Get Clean Data of Eartag in Birth Form: {}".format(eartag))
dam = self.cleaned_data.get('dam_id', '')
sire = self.cleaned_data.get('sire_id', '')
class Meta:
model = Birth_record
fields = ('dam', 'sire','eartag')
#index.html
{% extends 'base.html' %}
{% block content %}
<div class="container-fluid">
<div class="row">
<div class="col">
&emsp;
</div>
</div>
<div class="row px-3">
<div class="col">
<form method="post">
<span title="Last refresh at {%now 'D | F j o => h:i A e' %}">{% now "D | F j, o Z z j E" %}</span>
{% csrf_token %}
<div class="form-row py-2">
<div class="col col-lg-6">
<label><p class="font-weight-bold">Tag ID:&nbsp;<span class="text-danger">*</span></p></label>
<input type="number" name="eartag_id" class="form-control" min="1" required>
</div>
<div class="col">
<label><p class="font-weight-bold">Tag Color:&nbsp;<span class="text-danger">*</span></p></label>
<!--input type="text" name="eartag_color" list="color_list" class="form-control">
<datalist id="color_list">
<option>-- Choose Color --</option>
<option value="yellow"><span class="badge badge-warning">&emsp;</span>Yellow</option>
<option value="green">Green</option>
<option value="orange">Orange</option>
<option value="blue">Blue</option>
</datalist-->
<select name="eartag_color" class="form-control" required>
<option>-- Choose Color --</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="orange">Orange</option>
<option value="blue">Blue</option>
</select>
</div>
</div>
<div class="form-row py-2">
<div class="col">
<label><p class="font-weight-bold">Nickname:&nbsp;<span class="text-danger">*</span></p></label>
<input type="text" name="nickname" placeholder="Nickname (e.g. Wolf)" class="form-control" required>
</div>
</div>
<div class="form-row py-2">
<div class="col">
<label><p class="font-weight-bold">Gender:&nbsp;<span class="text-danger">*</span></p></label>
<select name="gender" class="form-control" required>
<option>-- Select Gender --</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
<div class="form-row py-2">
<div class="col">
<label><p class="font-weight-bold">Body Color:&nbsp;<span class="text-danger">*</span></p></label>
<input type="text" name="body_color" value="" placeholder="Body Color" class="form-control" required>
</div>
</div>
<div class="form-row py-2">
<div class="col">
<label><p class="font-weight-bold">Date of Birth:&nbsp;<span class="text-danger">*</span></p></label>
<input type="date" name="birth_date" placeholder="(e.g. mm/dd/yyyy)" class="form-control" required>
</div>
</div>
<div class="form-row py-2">
<div class="col">
<label><p class="font-weight-bold">Category:&nbsp;<span class="text-danger">*</span></p></label>
<label class="pl-5">
<input type="radio" name="category" value="birth">&emsp;By Birth</label>
<label>&emsp;
<input type="radio" name="category" value="purchase">&emsp;By Purchase</label>
</div>
</div>
<div class="row" id="birth_elem">
<div class="col">
<div class="container-fluid">
<div class="form-row py-2">
<div class="col">
<label><p class="font-weight-bold">Dam ID:&nbsp;<span class="text-danger">*</span></p></label>
<input type="number" name="dam_id" class="form-control" min="1" required>
</div>
</div>
<div class="form-row py-2">
<div class="col">
<label><p class="font-weight-bold">Sire ID:&nbsp;<span class="text-danger">*</span></p></label>
<input type="number" name="sire_id" class="form-control" min="1" required>
</div>
</div>
</div>
</div>
</div>
<div class="form-row">
<div class="col">
<label><p ><span class="font-weight-bold">Is castrated</span>
&nbsp;&nbsp;<input type="checkbox" name="is_castrated">
</p>
</label>
</div>
</div>
<div class="form-row mt-3 pr-5">
<button type="submit" class="font-weight-bold btn btn-success col-md-3 offset-md-9">Save</button>
</div>
</form>
</div>
</div>
{% endblock %}
## models.py
from django.db import models
# Create your models here.
from django.contrib.auth.models import User
class GoatProfile(models.Model):
STATUS = (
('active','Active'),
('sold','Sold'),
('deceased','Deceased'),
('lost','Lost'),
('stolen','Stolen'),
)
GENDER = (
('male','Male'),
('female','Female'),
)
TAG_COLOR = (
('yellow', 'Yellow'),
('green', 'Green'),
('orange', 'Orange'),
('blue', 'Blue'),
)
CATEGORY = (
('purchase', 'Purchase'),
('birth', 'Birth'),
)
eartag_id = models.IntegerField(primary_key=True)
eartag_color = models.CharField(max_length=250, choices=TAG_COLOR)
gender = models.CharField(max_length=10, choices=GENDER)
nickname = models.CharField(max_length=128)
body_color = models.CharField(max_length=64)
is_castrated = models.BooleanField()
status = models.CharField(max_length=32, choices=STATUS, default='active')
category = models.CharField(max_length=32, choices=CATEGORY)
birth_date = models.DateField()
class Meta:
db_table = 'goat_profile'
get_latest_by = 'birth_date'
ordering = ('eartag_id',)
class Birth_record(models.Model):
birth_id = models.AutoField(primary_key=True)
dam = models.ForeignKey(GoatProfile, related_name='dam_profile', on_delete=models.CASCADE)
sire = models.ForeignKey(GoatProfile, related_name='sire_profile', on_delete=models.CASCADE)
eartag = models.ForeignKey(GoatProfile, related_name='offspring_profile', on_delete=models.CASCADE)
class Meta:
ordering = ('birth_id', 'eartag_id',)
db_table = 'birth_record'
get_latest_by = 'birth_id'
def __str__(self):
return "%d is the offspring of %d (dam) and %d (sire)"%(self.eartag_id, self.dam_id, self.sire_id)
class Purchase_record(models.Model):
purchase_id = models.AutoField(primary_key=True)
purchase_weight = models.DecimalField(decimal_places=2, max_digits=8)
purchase_price = models.FloatField()
purchase_date = models.DateField(auto_now=True)
purchase_from = models.CharField(max_length=250)
eartag = models.ForeignKey(GoatProfile, related_name='purchase_goat', on_delete=models.CASCADE)
user = models.ForeignKey(User, related_name='goat_seller', on_delete=models.CASCADE)
class Meta:
ordering = ('purchase_id', '-purchase_date', 'eartag_id',)
db_table = 'purchase_record'
get_latest_by = 'purchase_date'
## views.py
from django.shortcuts import render
# Create your views here.
from .models import GoatProfile, Birth_record, Purchase_record
from .forms import GoatInfoForm
def index(request):
if request.method == 'POST':
form = GoatInfoForm(request.POST) #{}
if form.is_valid():
print("\n\n\n\nForm Successfully Validated\n\n")
cd = form.cleaned_data
goat_info = {
'eartag_id': cd['eartag_id'],
'eartag_color': cd['eartag_color'],
'nickname': cd['nickname'],
'gender': cd['gender'],
'body_color': cd['body_color'],
'category': cd['category'],
'is_castrated': cd['is_castrated'],
}
data = {}
#if cd['category'] == 'birth':
# data = {
# 'sire': cd['sire_id'],
# 'dam': cd['dam_id'],
# 'eartag': cd['eartag_id']
# }
#else:
# data = {
# 'purchase_weight': cd['purchase_weight'],
# 'purchase_price': cd['purchase_price'],
# 'purchase_date': cd['purchase_date'],
# 'purchase_from': cd['purchase_from'],
# 'eartag_id': cd['eartag_id'],
# 'user_id': request.user.id,
# }
else:
form = GoatInfoForm()
context = {
'title': "Django: the Web framework for perfectionists with deadlines.",
'form': form
}
return render(request, 'index.html', context)
#def custom_404(request):
## forms.py
from django import forms
# Create your forms here.
from django.contrib.auth.models import User
import re
class GoatInfoForm(forms.Form):
# STATUS = (
# ('active','Active'),
# ('sold','Sold'),
# ('deceased','Deceased'),
# ('lost','Lost'),
# ('stolen','Stolen'),
# )
GENDER = (
(None, '-- Please Select --'),
('male','Male'),
('female','Female'),
)
TAG_COLOR = (
(None, '-- Please Select --'),
('yellow', 'Yellow'),
('green', 'Green'),
('orange', 'Orange'),
('blue', 'Blue'),
)
CATEGORY = (
('purchase', 'Purchase'),
('birth', 'Birth'),
)
eartag_id = forms.IntegerField(min_value=1, widget=forms.widgets.NumberInput(attrs={'class':'form-control'}))
eartag_color = forms.ChoiceField(choices=TAG_COLOR, widget=forms.widgets.Select(attrs={'class': 'form-control'}))
nickname = forms.RegexField(regex='^[a-zA-Z]{3}[a-zA-Z ]+$', widget=forms.widgets.TextInput(attrs={'class': 'form-control'}))
gender = forms.ChoiceField(choices=GENDER, widget=forms.widgets.Select(attrs={'class': 'form-control'}))
body_color = forms.CharField(widget=forms.widgets.TextInput(attrs={'class': 'form-control'}))
category = forms.ChoiceField(choices=CATEGORY, widget=forms.widgets.RadioSelect(attrs={'class': 'form-check-input'}))
is_castrated = forms.BooleanField(required=False, widget=forms.widgets.CheckboxInput(attrs={'class': 'form-check-input'}))
#user_id = forms.IntegerField(widget=forms.widgets.HiddenInput())
#class Meta:
## index.html
{% extends 'app.html' %}
{% block content %}
<div class="container-fluid">
<div class="row">
<div class="col">
<section>
<form action="" method="POST">
{% csrf_token %}
<!--table>
{{ form.as_table }}
</table-->
<input type="hidden" name="user_id" value="{{ user.id}}">
<div class="form-row py-sm-2">
<label class="col-form-label-sm col-12 col-sm-4 col-md-2">
Eartag ID
</label>
<div class="col">
<input type="number" name="eartag_id" min="1" value="" class="form-control" placeholder="Eartag ID" required>
</div>
<label class="col-form-label-sm col-12 col-sm-2 col-md-2 text-lg-center">
Eartag Color
</label>
<div class="col">
<select name="eartag_color" class="custom-select" required>
<option value="">
-- Please Select --
</option>
<option value="yellow">
Yellow
</option>
<option value="green">
Green
</option>
<option value="orange">
Orange
</option>
<option value="blue">
Blue
</option>
</select>
</div>
</div>
<div class="form-row py-sm-2">
<label class="col-form-label-sm col-12 col-sm-4 col-md-2">
Nickname
</label>
<div class="col">
<input type="text" name="nickname" value="" class="form-control" placeholder="Nickname" required>
</div>
</div>
<div class="form-row py-sm-2">
<label class="col-form-label-sm col-12 col-sm-4 col-md-2">
Body Color
</label>
<div class="col">
<input type="text" name="body_color" value="" class="form-control" placeholder="Body Color" required>
</div>
</div>
<div class="form-row py-sm-2">
<label class="col-form-label-sm col-12 col-sm-4 col-md-2 ">
Gender
</label>
<div class="col">
<select name="gender" class="custom-select" required>
<option value="">
-- Please Select --
</option>
<option value="female">
Female
</option>
<option value="male">
Male
</option>
</select>
</div>
</div>
<div class="form-row pt-sm-2">
<label class="col-form-label-sm col-12 col-sm-4 col-md-2">
Category
</label>
<div class="col">
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="category" value="birth" required>
<label class="form-check-label">By Birth</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="category" value="purchase" required>
<label class="form-check-label">By Purchase</label>
</div>
</div>
</div>
<div class="form-row">
<label class="col-form-label-sm col-12 col-sm-4 col-md-2">
Is castrated
</label>
<div class="col">
<div class="container">
<div class="row">
<div class="col">
<label class="px-1">
<input type="checkbox" name="is_castrated" class="form-check-input">
<span class="form-text text-muted form-check form-check-inline" style="top: -3px"><small>For sire only</small></span>
</label>
</div>
</div>
</div>
</div>
</div>
<div class="form-row">
<button type="submit" class="font-weight-bolder btn btn-success col-md-3 offset-md-9" name="submit" id="save_btn" data-sys="save">Add New Goat</button>
</div>
</form>
</section>
</div>
</div>
</div>
{% endblock %}
## app.html
<!DOCTYPE html>
<html>
{% load static %}
<head>
<title>{{ title }}</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="{% static 'dist/css/bootstrap.min.css' %}">
</head>
<body>
{% block content %}
{% endblock %}
<!-- BEGIN:STARTER_TEMPLATE-->
<script src="{% static 'dist/js/jquery-3.3.1.slim.min.js' %}"></script>
<script src="{% static 'dist/js/bootstrap.min.js' %}"></script>
<script src="{% static 'dist/js/bootstrap.bundle.min.js' %}"></script>
<!-- END:STARTER_TEMPLATE -->
</body>
</html>
https://­www.youtube.com/­watch?v=8TYZp9Z0vsU
https://ccbv.co.uk/ this web is very very useful, it shows you how to use the classes
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from django.template import Context
from xhtml2pdf import pisa
def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
# return HttpResponse(html)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment