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.
//myapp/views.py
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib import messages
from myapp.models import Category, Post
category_list = Category.objects.exclude(status = 2).all()
context = {
'page_title' : 'Simple Blog Site',
'category_list' : category_list,
'category_list_limited' : category_list[:3]
}
# Create your views here.
#Logout
def logoutuser(request):
logout(request)
return redirect('/')
def home(request):
context['page_title'] = 'Home'
posts = Post.objects.filter(status = 1).all()
context['posts'] = posts
return render(request, 'home.html',context)
def view_post(request,pk=None):
context['page_title'] = ""
if pk is None:
messages.error(request,"Unabale to view Post")
return redirect('home-page')
else:
post = Post.objects.filter(id = pk).first()
context['page_title'] = post.title
context['post'] = post
return render(request, 'view_post.html',context)
def post_by_category(request,pk=None):
if pk is None:
messages.error(request,"Unabale to view Post")
return redirect('home-page')
else:
category = Category.objects.filter(id=pk).first()
context['page_title'] = category.name
context['category'] = category
posts = Post.objects.filter(category = category).all()
context['posts'] = posts
return render(request, 'by_categories.html',context)
def categories(request):
categories = Category.objects.filter(status = 1).all()
context['page_title'] = "Category Management"
context['categories'] = categories
return render(request, 'categories.html',context)
blogsite/urls.py
//blogsite/urls.py
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
path('summernote/', include('django_summernote.urls')),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
myspp/urls.py
//myspp/urls.py
from . import views
from django.contrib import admin
from django.urls import path, re_path
from django.contrib.auth import views as auth_views
from django.views.generic.base import RedirectView
urlpatterns = [
path('redirect-admin', RedirectView.as_view(url="/admin"),name="redirect-admin"),
path('', views.home, name="home-page"),
path('logout',views.logoutuser,name='logout'),
path(r'view_post/<int:pk>',views.view_post,name='view-post'),
path(r'<int:pk>',views.post_by_category,name='category-post'),
path('categories',views.categories,name='category-page'),
]
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\django\blogsite>python manage.py makemigrations
C:\django\blogsite>python manage.py migrate myapp/models.py
//myapp/models.py
from django.db import models
from unicodedata import category
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class Category(models.Model):
name = models.CharField(max_length=250)
description = models.TextField(blank=True, null=True)
status = models.IntegerField(default = 1)
date_added = models.DateTimeField(default=timezone.now)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Post(models.Model):
category=models.ForeignKey(Category,on_delete=models.CASCADE)
title = models.TextField()
author = models.ForeignKey(User,on_delete=models.CASCADE)
blog_post = models.TextField()
banner = models.ImageField(blank=True, null = True, upload_to= 'images/')
status = models.IntegerField(default = 0)
date_added = models.DateTimeField(default=timezone.now)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title + " - " + self.category.name
//myapp/admin.py
import django
from django.contrib import admin
from myapp.models import Category, Post
from django_summernote.admin import SummernoteModelAdmin
# Register your models here.
admin.site.register(Category)
#admin.site.register(Post)
class PostAdmin(SummernoteModelAdmin):
summernote_fields = ('blog_post',)
admin.site.register(Post, PostAdmin)
Run : C:\django\blogsite>python manage.py runserver
//myapp/views.py
from django.shortcuts import render
from .forms import ImageForm
from django.http import JsonResponse
def index(request):
form = ImageForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
return JsonResponse({'message': 'works'})
context = {'form': form}
return render(request, 'main.html', context)
devproject/urls.py
//devproject/urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls'))
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
myapp/urls.py
//myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\django\devproject>python manage.py makemigrations
C:\django\devproject>python manage.py migrate myapp/models.py
//myapp/models.py
from django.db import models
class Image(models.Model):
file = models.ImageField(upload_to='images')
uploaded = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.pk)
myapp/forms.py
//myapp/forms.py
from django import forms
from .models import Image
class ImageForm(forms.ModelForm):
class Meta:
model = Image
fields = ('file',)
//myapp/forms.py
from django import forms
from myapp.models import Member, City
class MemberCreationForm(forms.ModelForm):
class Meta:
model = Member
fields = '__all__'
widgets = { 'name': forms.TextInput(attrs={ 'class': 'form-control' }),
'email': forms.EmailInput(attrs={ 'class': 'form-control' }),
'country': forms.Select(attrs={ 'class': 'form-select' }),
'city': forms.Select(attrs={ 'class': 'form-select' }),
}
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')
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\django\devproject>python manage.py makemigrations
C:\django\devproject>python manage.py migrate myapp/models.py
//myapp/models.py
from django.db import models
class Country(models.Model):
name = models.CharField(max_length=40)
def __str__(self):
return self.name
class City(models.Model):
country = models.ForeignKey(Country, on_delete=models.CASCADE)
name = models.CharField(max_length=40)
def __str__(self):
return self.name
class Member(models.Model):
name = models.CharField(max_length=124)
email = models.CharField(max_length=125)
country = models.ForeignKey(Country, on_delete=models.SET_NULL, blank=True, null=True)
city = models.ForeignKey(City, on_delete=models.SET_NULL, blank=True, null=True)
def __str__(self):
return self.name
myapp/admin.py
//myapp/admin.py
from django.contrib import admin
# Register your models here.
from myapp.models import City, Country, Member
admin.site.register(City)
admin.site.register(Country)
admin.site.register(Member)
Model
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\django\blogsite>python manage.py makemigrations
C:\django\blogsite>python manage.py migrate myapp/models.py
#myapp/models.py
from django.db import models
# Create your models here.
class Post(models.Model):
post_title = models.CharField(max_length=200)
post_content = models.TextField()
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.pk)
class Meta:
ordering = ('-created',)
myapp/views.py
#myapp/views.py
from django.shortcuts import render
from django.views.generic import View, TemplateView
from .models import Post
from django.http import JsonResponse
class MainView(TemplateView):
template_name = 'main.html'
class PostJsonListView(View):
def get(self, *args, **kwargs):
print(kwargs)
upper = kwargs.get('num_posts')
lower = upper - 3
posts = list(Post.objects.values()[lower:upper])
posts_size = len(Post.objects.all())
max_size = True if upper >= posts_size else False
return JsonResponse({'data': posts, 'max': max_size}, safe=False)
blogsite/urls.py
#blogsite/urls.py
from django.contrib import admin
from django.urls import path
from myapp.views import MainView, PostJsonListView
urlpatterns = [
path('admin/', admin.site.urls),
path('', MainView.as_view(), name='main-view'),
path('posts-json/<int:num_posts>/', PostJsonListView.as_view(), name='posts-json-view'),
]
Run : C:\django\blogsite>python manage.py runserver
Python Django Ajax Login Register User Authentication with Profile and Upload Photo
Register App myapp and static file
//blogsite/settings.py
import os
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp', #add myapp
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = (
# location of your application, should not be public web accessible
'./static',
)
LOGIN_REDIRECT_URL = '/'
LOGIN_URL = '/login'
Creating View
myapp/views.py
//myapp/views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.urls import reverse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.decorators import login_required
import json
from django.contrib.auth.models import User
from django.contrib import messages
from myapp.models import UserProfile
from myapp.forms import UserRegistration, UpdateProfile, UpdateProfileMeta, UpdateProfileAvatar, AddAvatar
context = {
'page_title' : 'Blog Site'
}
# Create your views here.
def home(request):
context['page_title'] = 'Home'
return render(request, 'home.html',context)
def login_user(request):
logout(request)
resp = {"status":'failed','msg':''}
username = ''
password = ''
if request.POST:
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
resp['status']='success'
else:
resp['msg'] = "Incorrect username or password"
else:
resp['msg'] = "Incorrect username or password"
return HttpResponse(json.dumps(resp),content_type='application/json')
#Logout
def logoutuser(request):
logout(request)
return redirect('/')
def registerUser(request):
user = request.user
if user.is_authenticated:
return redirect('home-page')
context['page_title'] = "Register User"
if request.method == 'POST':
data = request.POST
form = UserRegistration(data)
if form.is_valid():
form.save()
newUser = User.objects.all().last()
try:
profile = UserProfile.objects.get(user = newUser)
except:
profile = None
if profile is None:
UserProfile(user = newUser, dob= data['dob'], contact= data['contact'], address= data['address'], avatar = request.FILES['avatar']).save()
else:
UserProfile.objects.filter(id = profile.id).update(user = newUser, dob= data['dob'], contact= data['contact'], address= data['address'])
avatar = AddAvatar(request.POST,request.FILES, instance = profile)
if avatar.is_valid():
avatar.save()
username = form.cleaned_data.get('username')
pwd = form.cleaned_data.get('password1')
loginUser = authenticate(username= username, password = pwd)
login(request, loginUser)
return redirect('home-page')
else:
context['reg_form'] = form
return render(request,'register.html',context)
@login_required
def profile(request):
context = {
'page_title':"My Profile"
}
return render(request,'profile.html',context)
@login_required
def update_profile(request):
context['page_title'] = "Update Profile"
user = User.objects.get(id= request.user.id)
profile = UserProfile.objects.get(user= user)
context['userData'] = user
context['userProfile'] = profile
if request.method == 'POST':
data = request.POST
form = UpdateProfile(data, instance=user)
if form.is_valid():
form.save()
form2 = UpdateProfileMeta(data, instance=profile)
if form2.is_valid():
form2.save()
messages.success(request,"Your Profile has been updated successfully")
return redirect("profile")
else:
context['form2'] = form2
else:
context['form1'] = form
form = UpdateProfile(instance=request.user)
return render(request,'update_profile.html',context)
@login_required
def update_avatar(request):
context['page_title'] = "Update Avatar"
user = User.objects.get(id= request.user.id)
context['userData'] = user
context['userProfile'] = user.profile
img = user.profile.avatar.url
context['img'] = img
if request.method == 'POST':
form = UpdateProfileAvatar(request.POST, request.FILES,instance=user)
if form.is_valid():
form.save()
messages.success(request,"Your Profile has been updated successfully")
return redirect("profile")
else:
context['form'] = form
form = UpdateProfileAvatar(instance=user)
return render(request,'update_avatar.html',context)
blogsite/urls.py
//blogsite/urls.py
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
myapp/urls.py
//myapp/urls.py
from . import views
from django.contrib import admin
from django.urls import path, re_path
from django.contrib.auth import views as auth_views
from django.views.generic.base import RedirectView
urlpatterns = [
path('redirect-admin', RedirectView.as_view(url="/admin"),name="redirect-admin"),
path('', views.home, name="home-page"),
path('login',auth_views.LoginView.as_view(template_name="login.html",redirect_authenticated_user = True),name='login'),
path('userlogin', views.login_user, name="login-user"),
path('user-register', views.registerUser, name="register-user"),
path('logout',views.logoutuser,name='logout'),
path('profile',views.profile,name='profile'),
path('update-profile',views.update_profile,name='update-profile'),
path('update-avatar',views.update_avatar,name='update-avatar'),
]
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\django\blogsite>python manage.py makemigrations
C:\django\blogsite>python manage.py migrate myapp/models.py
//myapp/models.py
from django.db import models
from django.contrib.auth.backends import BaseBackend
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,related_name='profile')
contact = models.CharField(max_length=250)
dob = models.DateField(blank=True, null = True)
address = models.TextField(blank=True, null = True)
avatar = models.ImageField(blank=True, null = True, upload_to= 'images/')
user_type = models.IntegerField(default = 2)
def __str__(self):
return self.user.username
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
def save_user_profile(sender, instance, **kwargs):
print(instance)
try:
profile = UserProfile.objects.get(user = instance)
except Exception as e:
UserProfile.objects.create(user=instance)
instance.profile.save()
myapp/forms.py
//myapp/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from myapp.models import UserProfile
class UserRegistration(UserCreationForm):
email = forms.EmailField(max_length=250,help_text="The email field is required.")
first_name = forms.CharField(max_length=250,help_text="The First Name field is required.")
last_name = forms.CharField(max_length=250,help_text="The Last Name field is required.")
class Meta:
model = User
fields = ('email', 'username', 'password1', 'password2', 'first_name', 'last_name')
def clean_email(self):
email = self.cleaned_data['email']
try:
user = User.objects.get(email = email)
except Exception as e:
return email
raise forms.ValidationError(f"The {user.email} mail is already exists/taken")
def clean_username(self):
username = self.cleaned_data['username']
try:
user = User.objects.get(username = username)
except Exception as e:
return username
raise forms.ValidationError(f"The {user.username} mail is already exists/taken")
class UpdateProfile(forms.ModelForm):
username = forms.CharField(max_length=250,help_text="The Username field is required.")
email = forms.EmailField(max_length=250,help_text="The Email field is required.")
first_name = forms.CharField(max_length=250,help_text="The First Name field is required.")
last_name = forms.CharField(max_length=250,help_text="The Last Name field is required.")
current_password = forms.CharField(max_length=250)
class Meta:
model = User
fields = ('email', 'username','first_name', 'last_name')
def clean_current_password(self):
if not self.instance.check_password(self.cleaned_data['current_password']):
raise forms.ValidationError(f"Password is Incorrect")
def clean_email(self):
email = self.cleaned_data['email']
try:
user = User.objects.exclude(id=self.cleaned_data['id']).get(email = email)
except Exception as e:
return email
raise forms.ValidationError(f"The {user.email} mail is already exists/taken")
def clean_username(self):
username = self.cleaned_data['username']
try:
user = User.objects.exclude(id=self.cleaned_data['id']).get(username = username)
except Exception as e:
return username
raise forms.ValidationError(f"The {user.username} mail is already exists/taken")
class UpdateProfileMeta(forms.ModelForm):
dob = forms.DateField(help_text="The Birthday field is required.")
contact = forms.CharField(max_length=250,help_text="The Contact field is required.")
address = forms.CharField(help_text="The Contact field is required.")
class Meta:
model = UserProfile
fields = ('dob', 'contact', 'address')
class UpdateProfileAvatar(forms.ModelForm):
avatar = forms.ImageField(help_text="The Avatar field is required.")
current_password = forms.CharField(max_length=250)
class Meta:
model = UserProfile
fields = ('avatar',)
def __init__(self,*args, **kwargs):
self.user = kwargs['instance']
kwargs['instance'] = self.user.profile
super(UpdateProfileAvatar,self).__init__(*args, **kwargs)
def clean_current_password(self):
if not self.user.check_password(self.cleaned_data['current_password']):
raise forms.ValidationError("Password is Incorrect")
class AddAvatar(forms.ModelForm):
avatar = forms.ImageField(help_text="The Avatar field is required.")
class Meta:
model = UserProfile
fields = ('avatar',)
myapp/admin.py
//myapp/admin.py
import django
from django.contrib import admin
from myapp.models import UserProfile
# Register your models here.
admin.site.register(UserProfile)
//myapp/models.py
from django.db import models
# Create your models here.
class Events(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255,null=True,blank=True)
start = models.DateTimeField(null=True,blank=True)
end = models.DateTimeField(null=True,blank=True)
class Meta:
db_table = "tblevents"
Make Migrations
Run the commands below to make migrations:
python manage.py makemigrations
python manage.py migrate
C:\django\devproject>python manage.py makemigrations
C:\django\devproject>python manage.py migrate
Creating View
myapp/views.py
//myapp/views.py
from django.shortcuts import render
from django.http import JsonResponse
from myapp.models import Events
# Create your views here.
def index(request):
all_events = Events.objects.all()
context = {
"events":all_events,
}
return render(request,'index.html',context)
def all_events(request):
all_events = Events.objects.all()
out = []
for event in all_events:
out.append({
'title': event.name,
'id': event.id,
'start': event.start.strftime("%m/%d/%Y, %H:%M:%S"),
'end': event.end.strftime("%m/%d/%Y, %H:%M:%S"),
})
return JsonResponse(out, safe=False)
def add_event(request):
start = request.GET.get("start", None)
end = request.GET.get("end", None)
title = request.GET.get("title", None)
event = Events(name=str(title), start=start, end=end)
event.save()
data = {}
return JsonResponse(data)
def update(request):
start = request.GET.get("start", None)
end = request.GET.get("end", None)
title = request.GET.get("title", None)
id = request.GET.get("id", None)
event = Events.objects.get(id=id)
event.start = start
event.end = end
event.name = title
event.save()
data = {}
return JsonResponse(data)
def remove(request):
id = request.GET.get("id", None)
event = Events.objects.get(id=id)
event.delete()
data = {}
return JsonResponse(data)