tutorial101 is the one place for high quality web development, Web Design and software development tutorials and Resources programming. Learn cutting edge techniques in web development, design and software development, download source components and participate in the community.
#view.py
from django.shortcuts import render
from django.db.models import Sum
from django.http import JsonResponse
from myapp.models import City
def home(request):
return render(request, 'home.html')
def population_chart(request):
labels = []
data = []
queryset = City.objects.values('name').annotate(population=Sum('population')).order_by('-population')
for entry in queryset:
labels.append(entry['name'])
data.append(entry['population'])
return JsonResponse(data={
'labels': labels,
'data': data,
})
urls.py
#urls.py
from django.contrib import admin
from myapp import views
from django.conf.urls import url
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('population-chart/', views.population_chart, name='population-chart'),
]
models.py
#models.py
from django.db import models
class City(models.Model):
name = models.CharField(max_length=30)
population = models.PositiveIntegerField()
def __str__(self):
return self.name
class Meta:
db_table = 'myapp_city'
How to Use Chart-js with Django Example Pie Chart
Chart.js is a open source JavaScript library that helps you render HTML5 charts.
In this tutorial we are going to Pie Chart based on data extracted from our models.
You can download it from Chart.js official website and use it locally, or you can use it from a CDN using the URL above.
https://www.chartjs.org/
myapp/models.py
#models.py
from django.db import models
class City(models.Model):
name = models.CharField(max_length=30)
population = models.PositiveIntegerField()
def __str__(self):
return self.name
class Meta:
db_table = 'myapp_city'
New database table added
CREATE TABLE myapp_article (
id INTEGER NOT NULL
PRIMARY KEY AUTOINCREMENT,
title VARCHAR (255) NOT NULL,
body TEXT NOT NULL,
slug VARCHAR (50) UNIQUE
);
urls.py
#urls.py
from django.contrib import admin
from django.urls import path
from myapp import views
from django.conf.urls import url
from myapp.views import ArticleListView, ArticleDetailView
urlpatterns = [
path('admin/', admin.site.urls),
path('', ArticleDetailView.as_view(), name='article_detail'),
path('', ArticleListView.as_view(), name='article_list'),
]
admins.py
#admin.py
from django.contrib import admin
from myapp.models import Article
class ArticleAdmin(admin.ModelAdmin):
list_display = ('title', 'body',)
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Article, ArticleAdmin)
views.py
#views.py
from django.shortcuts import render, redirect
from django.views.generic import ListView, DetailView
from myapp.models import Article
class ArticleListView(ListView):
model = Article
template_name = 'article_list.html'
class ArticleDetailView(DetailView):
model = Article
template_name = 'article_detail.html'
#admin.py
from django.contrib import admin
from myapp.models import Book
class BookAdmin(admin.ModelAdmin):
list_display = ['title', 'publication_date', 'author', 'price', 'book_type']
admin.site.register(Book, BookAdmin)
urls.py
#urls.py
from django.contrib import admin
from django.urls import path
from myapp import views
from django.conf.urls import url
from myapp.views import HomePageView, SearchResultsView
urlpatterns = [
path('admin/', admin.site.urls),
path('search/', SearchResultsView.as_view(), name='search_results'),
path('', HomePageView.as_view(), name='home'),
]
views.py
#views.py
from django.shortcuts import render, redirect
from django.views.generic import TemplateView, ListView
from myapp.models import Book
from django.db.models import Q
class HomePageView(TemplateView):
template_name = 'home.html'
# class SearchResultsView(ListView):
# model = Book
# template_name = 'search_results.html'
class SearchResultsView(ListView):
model = Book
template_name = 'search_results.html'
#queryset = Book.objects.filter(title__icontains='The Hobbit')
#def get_queryset(self): # new
# return Book.objects.filter(title__icontains='The Hobbit')
# def get_queryset(self):
# return Book.objects.filter(
# Q(title__icontains='The Hobbit') | Q(author__icontains='Cairocoders Ednalan')
# )
def get_queryset(self):
query = self.request.GET.get('q')
object_list = Book.objects.filter(
Q(title__icontains=query) | Q(author__icontains=query)
)
return object_list
How to Implement Token Authentication using Django REST Framework
In this tutorial you are going to learn how to implement Token-based authentication using Django REST Framework (DRF).
Django Authentication Sign Up, Login, Logout and Protecting Views
In this tutorial we are going to explore Django’s authentication system by implementing sign up, login, logout, and protected views from non-authenticated users.
Atom RSS Feed Generator with Python Flask
An Atom feed is very similar to an RSS feed in that it is a lightweight XML format allowing for easy syndication of web content. In fact, most RSS readers and news aggregators will be able to read Atom feeds just fine, as it is becoming a widely-used alternative to RSS feeds.
In this post we will generate feeds using python module called werkzeug.
feed_url = URL Route of Published Feed. Example : http://www.example.com/feeds
url = Root URL of Blog. Example : http://www.example.com
Once feed object is created we would call feed.add()
title = Post Title
summary = Blog post summary.
content_type = html Example : http://www.example.com
author = Name of author.
url = Absolute URL for the blog post. http://www.example.com/my-post
updated = Last updated date and time in UTC format.
published = Created date and time in UTC format.
#app.py
from flask import Flask, render_template, request
from werkzeug.contrib.atom import AtomFeed
from urllib.parse import urljoin
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///devdb.db'
app.config['SECRET_KEY'] = 'cairocoders-ednalan'
db = SQLAlchemy(app)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(140))
content = db.Column(db.String(140))
author_name = db.Column(db.String(140))
url = db.Column(db.String(140))
mod_date = db.Column(db.DateTime, default=datetime.utcnow)
created_date = db.Column(db.DateTime, default=datetime.utcnow)
def get_abs_url(url):
""" Returns absolute url by joining post url with base url """
return urljoin(request.url_root, url)
@app.route('/feeds/')
def feeds():
# feed = AtomFeed(title='Last 10 Posts from My Blog',
# feed_url="https://tutorial101.blogspot.com/feeds/",
# url="https://tutorial101.blogspot.com/")
feed = AtomFeed(title='Last 10 Posts from My Blog',
feed_url=request.url, url=request.url_root)
posts = Post.query.filter().all()
for post in posts:
feed.add(post.title, post.content,
content_type='html',
author= post.author_name,
url=get_abs_url(post.url),
updated=post.mod_date,
published=post.created_date)
return feed.get_response()
if __name__ == '__main__':
app.run(debug=True)
How to add ReCaptcha to Python Flask App without Extension
In this article we will learn to integrate Google ReCaptcha into flask web application without using any flask extension to prevent bots from submitting spam.
When you register for recaptcha it provides you two keys.
Site Key : For Client Side Integration
Secret Key : For Server Side Integration
Implementing ReCaptcha with python and flask app.py
#app.py
from flask import Flask, render_template, request, flash, redirect, url_for, json
import requests #pip install requests
app = Flask(__name__)
app.config['SECRET_KEY'] = 'cairocoders-ednalan'
def is_human(captcha_response):
""" Validating recaptcha response from google server
Returns True captcha test passed for submitted form else returns False.
"""
secret = "6LeKOaMZAAAAAKw9nhAjnpzrzrC3R0YYRf-kKDH1"
payload = {'response':captcha_response, 'secret':secret}
response = requests.post("https://www.google.com/recaptcha/api/siteverify", payload)
response_text = json.loads(response.text)
return response_text['success']
@app.route("/contact/", methods=["GET", "POST"])
def contact():
sitekey = "6LeKOaMZAAAAAI7L6TVsZa9A2t6-9LDVYSVqX9ZP"
if request.method == "POST":
name = request.form['name']
email = request.form['email']
msg = request.form['message']
captcha_response = request.form['g-recaptcha-response']
if is_human(captcha_response):
# Process request here
status = "Detail submitted successfully."
else:
# Log invalid attempts
status = "Sorry ! Please Check Im not a robot."
flash(status)
return redirect(url_for('contact'))
return render_template("contact.html", sitekey=sitekey)
if __name__ == '__main__':
app.run(debug=True)
How to add ReCaptcha to Flask App using Flask-reCaptcha
In this article we will learn to integrate Google ReCaptcha into flask web application using flask extension to prevent bots from submitting spam.
First install Flask-reCaptcha
pip install Flask-reCaptcha
https://pypi.org/project/Flask-reCaptcha/
Register Google ReCaptcha API
When you register for recaptcha it provides you two keys.
Site Key : For Client Side Integration
Secret Key : For Server Side Integration
Implementing ReCaptcha with python and flask app.py
How to Use RESTful APIs with Django
The REST acronym stands for Representational State Transfer, which is an architectural design.
Usually when we use the term RESTful
API stands for Application Programming Interface, which is a software application that we interact programmatically, instead of using a graphical interface.
RESTful API available the information you store in your databases using a common format, such as XML or JSON.
//templates/home.html
{% extends 'base.html' %}
{% block content %}
<h2>GEO API</h2>
<p>Your ip address is <strong>{{ ip }}</strong>, and you are probably in <strong>{{ country }}</strong> right now.</p>
<iframe width="900"
height="430"
frameborder="0"
style="border:0"
src="https://www.google.com/maps/embed/v1/view?center={{ latitude }},{{ longitude }}&zoom=8&key={{ api_key }}"
allowfullscreen></iframe>
{% endblock %}
Django Chained Dropdown List - Select Box using jQuery Ajax Country City
In this tutorial we are going to learn dynamic dependent select box using jquery, ajax Country and City.
This type of feature mostly use if you have use Country State City or you have working with Category
and you want to load Sub Category of particular category.
models.py
#models.py
from django.db import models
class Country(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Meta:
# managed = True
db_table = 'myapp_country'
class City(models.Model):
country = models.ForeignKey(Country, on_delete=models.CASCADE)
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Meta:
# managed = True
db_table = 'myapp_city'
class Person(models.Model):
name = models.CharField(max_length=100)
birthdate = models.DateField(null=True, blank=True)
country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True)
city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.name
class Meta:
# managed = True
db_table = 'myapp_person'
Database Table
CREATE TABLE myapp_country (
id INTEGER NOT NULL
PRIMARY KEY AUTOINCREMENT,
name VARCHAR (30) NOT NULL
);
INSERT INTO myapp_country (id, name) VALUES (1, 'Philippines');
INSERT INTO myapp_country (id, name) VALUES (2, 'United States');
INSERT INTO myapp_country (id, name) VALUES (3, 'Russia');
INSERT INTO myapp_country (id, name) VALUES (4, 'Brazil');
INSERT INTO myapp_country (id, name) VALUES (5, 'United Kingdom');
CREATE TABLE myapp_city (
id INTEGER NOT NULL
PRIMARY KEY AUTOINCREMENT,
name VARCHAR (30) NOT NULL,
country_id INTEGER NOT NULL
REFERENCES myapp_country (id) DEFERRABLE INITIALLY DEFERRED
);
CREATE TABLE myapp_person (
id INTEGER NOT NULL
PRIMARY KEY AUTOINCREMENT,
name VARCHAR (100) NOT NULL,
birthdate DATE,
city_id INTEGER REFERENCES myapp_city (id) DEFERRABLE INITIALLY DEFERRED,
country_id INTEGER REFERENCES myapp_country (id) DEFERRABLE INITIALLY DEFERRED
);
urls.py
#urls.py
from django.contrib import admin
from django.urls import path
from myapp import views
from django.conf.urls import url
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.PersonListView.as_view(), name='person_changelist'),
path('add/', views.PersonCreateView.as_view(), name='person_add'),
path('/', views.PersonUpdateView.as_view(), name='person_change'),
path('ajax/load-cities/', views.load_cities, name='ajax_load_cities'),
]
views.py
#views.py
from django.shortcuts import render, redirect
from django.views.generic import ListView, CreateView, UpdateView
from django.urls import reverse_lazy
from myapp.models import Person, City
from myapp.forms import PersonForm
class PersonListView(ListView):
model = Person
context_object_name = 'people'
template_name = 'person_list.html'
class PersonCreateView(CreateView):
model = Person
form_class = PersonForm
template_name = 'person_form.html'
success_url = reverse_lazy('person_changelist')
class PersonUpdateView(UpdateView):
model = Person
form_class = PersonForm
template_name = 'person_form.html'
success_url = reverse_lazy('person_changelist')
def load_cities(request):
country_id = request.GET.get('country')
cities = City.objects.filter(country_id=country_id).order_by('name')
return render(request, 'city_dropdown_list_options.html', {'cities': cities})
def load_cities(request): This view will be used via AJAX requests. forms.py
#forms.py
from django import forms
from myapp.models import Person, City
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ('name', 'birthdate', 'country', 'city')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['city'].queryset = City.objects.none()
if 'country' in self.data:
try:
country_id = int(self.data.get('country'))
self.fields['city'].queryset = City.objects.filter(country_id=country_id).order_by('name')
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['city'].queryset = self.instance.country.city_set.order_by('name')
templates/person_list.html
//templates/person_list.html
{% extends 'base.html' %}
{% block title %}Django Chained Dropdown List - Select Box using jQuery Ajax Country City{% endblock %}
{% block content %}
<table class="table table-striped custab">
<thead>
<a href="{% url 'person_add' %}" class="btn btn-primary btn-xs pull-right"><b>+</b> Add new Person</a>
<tr>
<th>Name</th>
<th>Birthdate</th>
<th>Country</th>
<th>City</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tbody>
{% for person in people %}
<tr>
<td><a href="{% url 'person_change' person.pk %}">{{ person.name }}</a></td>
<td>{{ person.birthdate }}</td>
<td>{{ person.country.name }}</td>
<td>{{ person.city.name }}</td>
<td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
</tr>
{% empty %}
<tr>
<td colspan="4">No person in the database. <a href="{% url 'person_add' %}">Add the first person</a>.</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
Django How to Add reCAPTCHA to a Django Site
Google’s reCAPTCHA is a very popular solution to protect your application or website against bots and spam.
In this tutorial I will show how to How to Add reCAPTCHA to a Django Site
First, register your application in the reCAPTCHA admin. https://www.google.com/recaptcha/admin
#views.py
import json
import urllib
from django.shortcuts import render, redirect
from django.conf import settings
from django.contrib import messages
from myapp.models import Comment
from myapp.forms import CommentForm
def comments(request):
comments_list = Comment.objects.order_by('-created_at')
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
recaptcha_response = request.POST.get('g-recaptcha-response')
url = 'https://www.google.com/recaptcha/api/siteverify'
values = {
'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
'response': recaptcha_response
}
data = urllib.parse.urlencode(values).encode()
req = urllib.request.Request(url, data=data)
response = urllib.request.urlopen(req)
result = json.loads(response.read().decode())
if result['success']:
form.save()
messages.success(request, 'New comment added with success!')
else:
messages.error(request, 'Invalid reCAPTCHA. Please try again.')
return redirect('comments')
else:
form = CommentForm()
return render(request, 'comments.html', {'comments': comments_list, 'form': form})
models.py
#models.py
from django.db import models
class Comment(models.Model):
text = models.TextField(max_length=1000)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
db_table = "comments"
forms.py
#forms.py
from django import forms
from myapp.models import Comment
class CommentForm(forms.ModelForm):
text = forms.CharField(
widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '3'}),
required=True,
max_length=1000
)
class Meta:
model = Comment
fields = ('text', )
urls.py
#urls.py
from django.contrib import admin
from django.urls import path
from myapp import views
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^comments/$', views.comments, name='comments'),
]
#filters.py
from django.contrib.auth.models import User
import django_filters
class UserFilter(django_filters.FilterSet):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', ]
views.py
#views.py
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from myapp.filters import UserFilter
def search(request):
user_list = User.objects.all()
user_filter = UserFilter(request.GET, queryset=user_list)
return render(request, 'user_list.html', {'filter': user_filter})
urls.py
#urls.py
from django.contrib import admin
from django.urls import path
from myapp import views
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^search/$', views.search, name='search'),
]
Django How to Add User Profile To Admin
You want to store a few more data related to User. This is how to extend the the default Django User model User Profile admin
Database Table
CREATE TABLE myapp_profile (
id INTEGER PRIMARY KEY,
user_id INTEGER,
location STRING (200),
birthdate DATE,
role INTEGER
);
models.py
#models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
STUDENT = 1
TEACHER = 2
SUPERVISOR = 3
ROLE_CHOICES = (
(STUDENT, 'Student'),
(TEACHER, 'Teacher'),
(SUPERVISOR, 'Supervisor'),
)
user = models.OneToOneField(User, on_delete=models.CASCADE)
location = models.CharField(max_length=30, blank=True)
birthdate = models.DateField(null=True, blank=True)
role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, null=True, blank=True)
def __str__(self): # __unicode__ for Python 2
return self.user.username
class Meta:
db_table = "myapp_profile"
@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
admins.py
#admin.py
from django.contrib import admin
from myapp.models import Profile
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
class ProfileInline(admin.StackedInline): #StackedInline normally is used for formsets
model = Profile
can_delete = False
verbose_name_plural = 'Profile'
fk_name = 'user'
class CustomUserAdmin(UserAdmin):
inlines = (ProfileInline, )
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'get_location') #Add Profile Fields to List View
list_select_related = ('profile', )
def get_location(self, instance):
return instance.profile.location
get_location.short_description = 'Location'
def get_inline_instances(self, request, obj=None): #get_inline_instances display the inlines only in the edit form
if not obj:
return list()
return super(CustomUserAdmin, self).get_inline_instances(request, obj)
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)