Sending an email with html template and attachment files in django
April 11, 2022, 8:03 p.m.
98sending an email with HTML template and attachment files in Django
view.py
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
# email for user details view
def user_details_mail(request, user_id=None):
# print('hi=', rfq_id)
context = {}
if request.method == 'POST':
email_to = request.POST['email_to']
cc = request.POST['cc']
usr_message = request.POST['message']
subject = request.POST['subject']
user_details = USR_Details.objects.filter(usr_id=user_id)
context['title'] = "test mail"
context['usr_message'] = usr_message
context['usr_details'] = usr_details
html_context = render_to_string(
"myapp/detail_mail_template.html", context)
text_content = strip_tags(html_context)
email = EmailMultiAlternatives(subject=subject,
body=text_content,
from_email='[email protected]',
to=email_to.strip('][').split(','),
# bcc=['[email protected]', '[email protected]'],
cc=cc.strip('][').split(',')
# connection=connection
)
email.attach_alternative(html_context, "text/html")
file = request.FILES.getlist('file')
for file in file:
email.attach(file.name, file.read(), file.content_type)
email.send()
messages.success(request, "Email sent successfully.")
return redirect("home")
else:
user_details _details = USR_Details.objects.filter(usr_id=user_id)
context['usr_details'] = usr_details
# print('im here')
return render(request, 'mail.html', context)
def home(request):
return render(request,'home.html')
urls.py
from django.contrib import admin
from django.urls import path
from MyApp import views
urlpatterns = [
path("admin/", admin.site.urls),
path("", views.home, name="home"),
path("mailsub", views.mailsub, name="mailsub"),
]
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
{% if message %}
{{message}}
{% else %}
<form method="POST" action="{% url 'mailsub' %}">
{% csrf_token %}
<input name="email_to" placeholder="subject" />
<input name="subject" placeholder="subject" />
<input name="message_email" placeholder="user email" />
<input name="message" placeholder="your message" />
<input type="submit" value="submit" />
<div class="btn-toolbar" role="toolbar">
<div class="input-group">
<div class="input-group-prepend ">
<span class="input-group-text"
id="inputGroupFileAddon01">Attach File</span>
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" id="file"
name="file"
multiple
aria-describedby="inputGroupFileAddon01">
<label class="custom-file-label" id="filenames"
for="inputGroupFile01">Choose
file</label>
</div>
</div>
</div>
</form>
{% endif %}
</body>
</html>
detail_mail_template.html
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<!-- <link rel='stylesheet' type='text/css' media='screen' href='main.css'>
<script src='main.js'></script> -->
</head>
<body>
<pre style="margin: 0; font-size: 11pt; font-family: Calibri, sans-serif;">{{ usr_message }}</pre>
<br>
{% for i in user_details %}
<div class="table-responsive">
<table border=1>
<tr>
<th>userInfo</th>
<th>Details</th>
</tr>
<tr>
<td>
user ID
</td>
<td>
{{ i.user_id }}
</td>
</tr>
<tr>
<td>
Action
</td>
<td>
{{ i.username}}
</td>
</tr>
<tr>
<td>
File Name
</td>
<td>
{{ i.file_name }}
</td>
</tr>
</table>
</div>
<br>
{% endfor %}
<pre style="margin: 0; font-size: 11pt; font-family: Calibri, sans-serif;"> {{ signature }}</pre>
</body>
</html>
What is macros in jinja template in django
April 11, 2022, 5:01 p.m.
20what are Macros in the jinja template in Django?
Macros are comparable with functions in regular programming languages. They are useful to put often used idioms into reusable functions to not repeat yourself (“DRY”).
home.html
{% macro input(name, value='', type='text', size=20) -%}
<input type="{{ type }}" name="{{ name }}" value="{{
value|e }}" size="{{ size }}">
{%- endmacro %}
The macro can then be called like a function in the namespace:
<p>{{ input('username') }}</p>
<p>{{ input('password', type='password') }}</p>
If the macro was defined in a different template, you have to import it first.
How to create multiple views.py in django
April 11, 2022, 4:56 p.m.
16How to create multiple views.py in Django
when we create an application in Django then we can not write complete code on views.py because if a line of code will be exceeded then the application load time will be increased.
We can create multiple views.py to refactor the code on multiple files which will be better for the understandability of the code and reduce file load.
Step to create another views.py
1) go into the app and create one python file, I provided the name myviews.py
and write the following code
from django.shortcuts import render
def welcome(request):
return render(request,"databinding/welcome.html")
2) create.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Welcome to kwikl3arn</h1>
</body>
</html>
3) urls.py
from django.urls import path
from . import myview
urlpatterns=[
path('welcome',myview.welcome,name='welcome')
]
How to work with the orm queries
April 9, 2022, 12:30 a.m.
30How to work with the ORM Queries
Creating Table in Database using Model
First, we will create a sample database using the Django model that consists of some data and we will run the query on that database.
model.py
# Create your models here.
class Student(models.Model):
username = models.CharField(max_length=20)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
mobile = models.CharField(max_length=10)
email = models.EmailField()
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
And then run the following command.
python manage.py makemigrations
python manage.py migrate
We are set to run the query.
How to get all records from a table(Model)
We have a model called Student. To get all records from the model, we will use the Student.objects.all(). To do so, open the Django shell to run the query.
>>> from sampleapp.models import Student
>>> queryset = Student.objects.all()
>>> queryset
<QuerySet [<Student: Ritesh Tiwari>, <Student: Yash Sharma>, <Student: Arpita Sharma>, <Student: Prince Sharma>, <Student: Megha Bhardwaj>, <Student: Akash Mishra>]>
You might be wondering how Django ORM makes our queries executed or what the corresponding query of the code we are writing. It is quite simple to get the SQL
query, we need to use the str() and pass the queryset object along with the query.
Corresponding SQL Query
>>> str(queryset.query)
'SELECT "sampleapp_student"."id", "sampleapp_student"."username", "sampleapp_student"."first_name", "sampleapp_student"."last_name", "sampleapp_student"."mobile", "sampleapp_student"."email" FROM "sampleapp_student"'
How to add record to table(Model)
We will use the Student.objects.create() and pass the fields along with their value as argument. Let's see the below example.
>>> queryset = Student.objects.create(username = 'rahul20', first_name = 'Rahul', last_name = 'Shakya', mobile = '77777', email = '[email protected]')
>>> queryset.save()
Note that, we need to use the .save() method on the query object to save the newly created record in a table, otherwise it will not show in the database.
Retrieving Single Objects from QuerySets
Suppose we need a specific object from a queryset to matching the result. We can do this using the get() method. The get() returns the single object directly. Let's see the following example.
Example -1
>>> from sampleapp.models import Student
>>> queryset = Student.objects.get(pk = 1)
>>> queryset
<Student: Ritesh Tiwari>
Example - 2
>>> queryset = Student.objects.get(mobile = 22222)
>>> queryset
<Student: Yash Sharma>
As we can see in both examples, we get the single object not a queryset of a single object. If there is no result then match the query, get() will raise a DoesNotExist exception. On the other hand, if there is multiple field matches, it will raise the MultipleObjectReturned, which is an attribute of the model class itself.
Filtering the Records
In the earlier example, the QuerySet returned by all() describes the all record in the database table. But sometimes, we need to select the subset of complete set of object and it can be done by adding the filter conditions.
In the below example, we will fetch the data which first name starts with the R.
>>> queryset = Student.objects.filter(first_name__startswith = 'R')
>>> queryset
output:
<QuerySet [<Student: Ritesh Tiwari>, <Student: Rahul Shakya>]>
>>> str(queryset.query)
output:
'SELECT "sampleapp_student"."id", "sampleapp_student"."username", "sampleapp_student"."first_name", "sampleapp_student"."last_name", "sampleapp_student"."mobile", "sampleapp_student"."email" FROM "sampleapp_student" WHERE "sampleapp_student"."first_name" LIKE R% ESCAPE \'\\\''
Note - The difference between get() and filter() method is that, the filter() method returns the queryset of object(s) where get() method returns single object.
Using exclude() Method
It returns a new QuerySet containing objects that do not match the given lookup parameter. In other words, it excluded the records according to the lookup condition. Let's understand the following example.
>>> queryset = Student.objects.exclude(first_name__startswith = 'R')
>>> queryset
output:
, , , , ]>
How to make OR queries in Django ORM?
The OR operation is performed when we need the record filtering with two or more conditions. In the below example, we will get the student whose first_name starts with 'A' and last_name starts with 'M'.
Django allows us to do this in two ways.
- queryset_1 |queryset_2
- filter(Q(<condition_1>) | Q(<condition_2>
>>> queryset = Student.objects.filter(first_name__startswith = 'P') & Student.objects.filter(last_name__startswith = 'S')
>>> queryset
<QuerySet [<Student: Prince Sharma>]>
Only one object satisfied the given conditions.
We can also use the following query.
queryset2 = User.objects.filter( first_name__startswith='A', last_name__startswith='S' )
or
queryset3 = User.objects.filter(Q(first_name__startswith='R') & Q(last_name__startswith='D') )
All queries will give the same result.
Creating Multiple Object in One Shot
Sometimes we want create multiple objects in one shot. Suppose we want to create new objects at once and we don't want to run the multiple queries to the database. Django ORM provides the bulk_create to create multiple objects in one way.
>>> Student.objects.all().count()
7
Let's create the multiple records in one query.
Student.objects.bulk_create([Student(first_name = 'Jai', last_name = 'Shah', mobile = '88888', email = '[email protected]'),Student(first_name = 'Tarak', last_name = 'Mehta', mobile = '9999', email = '[email protected]'), Student(first_name = 'SuryaKumar', last_name = 'Yadav', mobile = '00000', email = '[email protected]')])
[<Student: Jai Shah>, <Student: Tarak Mehta>, <Student: SuryaKumar Yadav>]
Now, our database table will update. The bulk_create takes a list of unsaved objects.
>>> Student.objects.all().count()
10
Limiting QuerySets
We can set the limit on the queryset using the Python list's slicing syntax. This is equivalent operation of SQL's LIMIT and OFFSET clauses. Let's see the following query.
>>> Student.objects.all()[:4]
<QuerySet [<Student: Ritesh Tiwari>, <Student: Yash Sharma>, <Student: Arpita Sharma>, <Student: Prince Sharma>]>
Below query will return first record to fifth record.
>>> Student.objects.all()[1:6]
<QuerySet [<Student: Yash Sharma>, <Student: Arpita Sharma>, <Student: Prince Sharma>, <Student: Megha Bhardwaj>, <Student: Akash Mishra>]>
Negative indexing is not supported. However, we can use the step in QuerySets.
>>> Student.objects.all()[:10:2]
[<Student: Ritesh Tiwari>, <Student: Arpita Sharma>, <Student: Megha Bhardwaj>, <Student: Rahul Shakya>, <Student: Tarak Mehta>]
To fetch the single record, we can do the following operation.
>>> Student.objects.all()[0]
<Student: Ritesh Tiwari>
How to order QuerySets in ascending or descending order?
Django provides the order_by method for ordering the queryset. This method takes the field name which we want to Order (ascending and descending) the result. Let's see the following example.
Example - Ascending order
>>> from sampleapp.models import Student
>>> Student.objects.all().order_by('mobile')
<QuerySet [<Student: SuryaKumar Yadav>, <Student: Ritesh Tiwari>, <Student: Yash Sharma>, <Student: Arpita Sharma>, <Student: Prince Sharma>, <Student: Megha Bhardwaj>, <Student: Akash Mishra>, <Student: Rahul Shakya>, <Student: Jai Shah>, <Student: Tarak Mehta>]>
For descending order, we will use the Not '-' before the query field.
>>> from sampleapp.models import Student
>>> Student.objects.all().order_by('-mobile')
<QuerySet [<Student: Tarak Mehta>, <Student: Jai Shah>, <Student: Rahul Shakya>, <Student: Akash Mishra>, <Student: Megha Bhardwaj>, <Student: Prince Sharma>, <Student: Arpita Sharma>, <Student: Yash Sharma>, <Student: Ritesh Tiwari>, <Student: SuryaKumar Yadav>]>
We can also pass the multiple fields in the order_by function.
>>> Student.objects.all().order_by('first_name','-mobile')
<QuerySet [<Student: Akash Mishra>, <Student: Arpita Sharma>, <Student: Jai Shah>, <Student: Megha Bhardwaj>, <Student: Prince Sharma>, <Student:
Rahul Shakya>, <Student: Ritesh Tiwari>, <Student: SuryaKumar Yadav>, <Student: Tarak Mehta>, <Student: Yash Sharma>]>
How to order on a field from a related model (with foreign key)?
Now, we will learn how we can order the data in the relation model. We create another model called Teacher which is a related model of Student model.
Models
class Teacher(models.Model):
teacher_name = models.CharField(max_length=200)
def __str__(self):
return f'{self.teacher_name}'
class Student(models.Model):
username = models.CharField(max_length=20)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
mobile = models.CharField(max_length=10)
email = models.EmailField()
teacher_name = models.ForeignKey(Teacher, blank = True, null = True, on_delete= models.CASCADE)
We have added the teachers' names and each teacher is associated with the student. Now we want to order Student by teacher_name inside each teacher_name by the Student. We can do as follows.
>>> Student.objects.all().order_by('teacher__id', 'first_name')
<QuerySet [<Student: Prince Sharma>, <Student: Ritesh Tiwari>, <Student: SuryaKumar Yadav>, <Student: Tarak Mehta>, <Student: Arpita Sharma>, <Student: Megha Bhardwaj>, <Student: Jai Shah>, <Student: Rahul Shakya>, <Student: Yash Sharma>, <Student: Akash Mishra>]>
Important Field Lookups
Query field lookups are nothing but a condition that specifies the same as the SQL WHERE clause. They are stated as keyword arguments to the QuerySet methods such as filter(), exclude(), and get().
Example -
Student.objects.filter(first_name__startswith = 'Ritesh')
<QuerySet [<Student: Ritesh Tiwari>]>
This is the same as the following SQL query
Select * from Student where first_name = "Ritesh"
Let's understand some important lookups.
exact
It returns the exact result according to the search.
>>> Student.objects.get(first_name__exact = 'Arpita')
<Student: Arpita Sharma>
The lookup should be used after the __ double underscore. We can use the case-insensitive version called iexact.
contains
It is used for case-sensitive tests. Let's see the following example.
>>> from sampleapp.models import Student
>>> Student.objects.filter(last_name__contains = 'Shar')
<QuerySet [<Student: Yash Sharma>, <Student: Arpita Sharma>, <Student: Prince Sharma>]>
If we translate the SQL query then it will look like as below.
SELECT ... WHERE last_name LIKE '%Shar%';
There is also a case-incentive version called icontains.
How to perform join operations in Django
The SQL join combines data or rows from two or more tables based on a common field between them. We can perform join operations in many ways. Let's understand the following example.
>>> q = Student.objects.select_related('teacher')
>>>q
<QuerySet [<Student: Ritesh Tiwari>, <Student: Yash Sharma>, <Student: Arpita Sharma>, <Student: Prince Sharma>, <Student: Megha Bhardwaj>, <Student: Akash Mishra>, <Student: Rahul Shakya>, <Student: Jai Shah>, <Student: Tarak Mehta>, <Student: SuryaKumar Yadav>]>
>>>print(q.query)
SELECT "sampleapp_student"."id", "sampleapp_student"."username", "sampleapp_student"."first_name", "sampleapp_student"."last_name", "sampleapp_student"."mobile", "sampleapp_student"."email", "sampleapp_student"."teacher_id", "sampleapp_teacher"."id", "sampleapp_teacher"."teacher_name" FROM "sampleapp_student" LEFT OUTER JOIN "sampleapp_teacher" ON ("sampleapp_student"."teacher_id" = "sampleapp_teacher"."id")
How to group record in Django ORM?
Django ORM provides the grouping facility using the aggregation functions like Max, Min, Avg, and Sum. Sometimes we need to get the aggregate values from the objects. Let's understand the following example.
>>> from django.db.models import Avg, Max, Min, Sum, Count
>>> Student.objects.all().aggregate(Avg('id'))
{'id__avg': 5.5}
>>> Student.objects.all().aggregate(Min('id'))
{'id__min': 1}
>>> Student.objects.all().aggregate(Max('id'))
{'id__max': 10}
>>> Student.objects.all().aggregate(Sum('id'))
{'id__sum': 55}
How to perform truncate like operation using Django ORM?
Truncate in SQL means clear the table data for future use. Django doesn't provide the built-in methods to truncate the table, but we can use the delete() method to get the similar result. Let's understand the following example.
>>> Student.objects.all().count()
10
>>> Student.objects.all().delete()
(10, {'sampleapp.Student': 10})
>>> Student.objects.all().count()
0
>>> Student.objects.all()
<QuerySet []>
If you want to delete the individual object instance, you need to call delete() method on the individual instances of that model. We have called the delete() method on model so it deleted the entire data.
How to get union of Data
Union means getting the record which are common in both query sets. Let's see how we can do this.
>>> q1 = Student.objects.filter(id__gte = 15)
>>> q1
<QuerySet [<Student: Megha Bhardwaj>, <Student: Akash Mishra>]>
>>> q2 = Student.objects.filter(id__lte = 15)
>>> q2
<QuerySet [<Student: Ritesh Tiwari>, <Student: Yash Sharma>, <Student: Arpita Sharma>, <Student: Prince Sharma>, <Student: Megha Bhardwaj>]>
>>> q1.union(q2)
<QuerySet [<Student: Ritesh Tiwari>, <Student: Yash Sharma>, <Student: Arpita Sharma>, <Student: Prince Sharma>, <Student: Megha Bhardwaj>, <Student: Akash Mishra>]>
What is difference between null=True and blank=True?
In Django, we use null and blank often, by default their values are False. Both of these value work at field level where we want to keep a field null or blank. Both values seem similar but they are different in use.
If null=True means the field value is set as NULL i.e. no data. It is basically for the database column value.
date = models.DateTimeField(null=True)
The blank = True specifies whether field is required in forms.
title = models.CharField(blank=True) // title can be kept blank. In the database ("") will be stored.
If we set null=True blank=True, means that the field is optional in all circumstances.
teacher = models.ForeignKey(null=True, blank=True) // The exception is CharFields() and TextFields(), which in Django are never saved as ?→NULL. Blank values are stored in the DB as an empty string ('').
Create a login, logout, forgot password, user, and edit a user in django views
April 8, 2022, 6:25 p.m.
25create a login, logout, forgot password, user, and edit a user in Django views
urls.py
from django.views.generic.base import TemplateView
from django.contrib.auth import views as auth_views #import this
urlpatterns = [
path('login', views.login_page, name='login'),
path('logout', views.logout_view, name='logout'),
path('password',auth_views.PasswordChangeView.as_view(template_name='templates/change-
password.html',success_url = '/'), name='password'),
# change password end
path('edit_profile', views.UserEditview.as_view(), name='edit_profile'),
path('register', views.UserCreateview.as_view(), name='register'),
# Forgot Password --start
path('password_change/', views.PasswordChangeView.as_view(template_name='templates/password_reset/password_change.html'), name='password_change'),
path('password_reset',views.password_reset_request,name='password_reset'),
path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='templates/password_reset/password_reset_done.html'), name='password_reset_done'),
path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='templates/password_reset/password_reset_confirm.html'), name='password_reset_confirm'),
path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='templates/password_reset/password_reset_complete.html'), name='password_reset_complete'),
# Forgot Password --end
]
forms.py
from django.contrib.auth.models import User
from crispy_forms.helper import FormHelper
from django.forms import ModelForm
from django import forms
from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm, UserCreationForm
from django.forms import ClearableFileInput
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class PasswordChangeForm(PasswordChangeForm):
class Meta:
# specify model to be used
model = User
# specify fields to be used
fields = "__all__"
class Create_Profile_Form(UserCreationForm):
# ---removing all form label by using crispy_forms
def __init__(self, *args, **kwargs):
super(Create_Profile_Form, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_show_labels = False
class Meta:
model = User
fields = ('first_name', 'last_name', 'username', 'email', 'password1', 'password2')
class Edit_Profile_Form(UserChangeForm):
# ---removing all form label by using crispy_forms
def __init__(self, *args, **kwargs):
super(Edit_Profile_Form, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_show_labels = False
class Meta:
# specify model to be used
model = User
# specify fields to be used
fields = "__all__"
# class PasswordChangeForm(PasswordChangeForm):
# class Meta:
# # specify model to be used
# model = User
# # specify fields to be used
# fields = "__all__"
class Update_PasswordChangeForm(PasswordChangeForm):
class Meta:
# specify model to be used
model = User
# specify fields to be used
fields = "__all__"
view.py
from qc_app.forms import Edit_Profile_Form, Update_PasswordChangeForm, Create_Profile_Form, RegistrationNumberForm
from django.views import generic
from django.contrib.auth.forms import UserChangeForm
# login validation view
def login_page(request):
# print('--------------------------------------')
# print('now in login_page')
if request.user.is_authenticated:
return redirect(settings.LOGIN_REDIRECT_URL)
elif request.method == "POST":
# print(request.POST)
username = request.POST.get('InputEmail1')
password = request.POST.get('InputPassword1')
user = authenticate(request, username=username, password=password)
if user is None:
User = get_user_model()
user_queryset = User.objects.all().filter(email__iexact=username)
if user_queryset:
username = user_queryset[0].username
user = authenticate(username=username, password=password)
if user is not None:
print('in login')
# request.session.set_expiry(57600) # session expire in 4 hrs
login(request, user) # the user is now logged in
# print('user loged in:', request.user.is_authenticated)
# if user clicked something which is required login,
# after login it will redirect to that page,what ever user clicked
if 'next' in request.GET:
return redirect(request.GET['next'])
else:
return redirect('home')
else:
return render(request, 'templates/login.html', context={'msg': 'Invalid Email / Password'})
else:
return render(request, 'templates/login.html', context={})
def home(request):
return render(request, 'templates/home.html')
# logout view
def logout_view(request):
logout(request)
return redirect('home')
# user edit view
class UserCreateview(LoginRequiredMixin, generic.CreateView):
form_class = Create_Profile_Form
template_name = 'templates/create_user.html'
success_url = reverse_lazy('login')
def get_object(self, queryset=None):
return self.request.user
# user edit view
class UserEditview(LoginRequiredMixin, generic.UpdateView):
form_class = Edit_Profile_Form
template_name = 'edit_profile.html'
success_url = reverse_lazy('home')
def get_object(self, queryset=None):
return self.request.user
# Forgot Password --start
from .forms import Update_PasswordChangeForm
from django.contrib.auth.views import PasswordChangeView
from django.contrib.auth.forms import PasswordResetForm
from django.contrib.sites.shortcuts import get_current_site
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.utils.encoding import force_bytes, force_text
from django.contrib.auth.tokens import default_token_generator
def password_reset_request(request):
if request.method == "POST":
password_reset_form = PasswordResetForm(request.POST)
if password_reset_form.is_valid():
data = password_reset_form.cleaned_data['email']
associated_users = User.objects.filter(email=data)
if associated_users.exists():
for user in associated_users:
subject = "Password Reset Requested"
current_site = get_current_site(request)
message = render_to_string('templates/password_reset/password_reset_email.html', {
#'referal_code':referal_code,
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': default_token_generator.make_token(user),
'protocol':'http',
})
try:
send_mail(subject, message, '[email protected]' , [user.email])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect ("/password_reset/done/")
# messages.success(request, 'A message with reset password instructions has been sent to your inbox.')
# return redirect ("home")
else:
errors="Email Does not exists"
return render(request=request, template_name="templates/password_reset/password_reset.html", context={"password_reset_form":password_reset_form,"errors":errors})
password_reset_form = PasswordResetForm()
print("password form",password_reset_form)
return render(request=request, template_name="templates/mpassword_reset/password_reset.html", context={"password_reset_form":password_reset_form})
# Forgot Password --end
templates/create_user.html
{% extends 'templates/base.html' %} {% load crispy_forms_tags %}
{% block title %}
<title>Create User</title>
{% endblock %}
{% block body %}
<style>
.submit_button {
padding: 0.84rem 2.14rem;
font-size: .81rem;
margin: auto;
padding-top: .7rem;
padding-bottom: .7rem;
background-color: tomato;
color: white;
}
.container {
padding-top: 0.5rem;
margin: auto;
}
.field-icon {
float: right;
margin-left: -25px;
margin-top: -63px;
margin-right: 10px;
position: relative;
z-index: 2;
}
.field-icon1 {
float: right;
margin-left: -25px;
margin-top: -122px;
margin-right: 10px;
position: relative;
z-index: 2;
}
</style>
<div class="text-center mt-5">
<h3 class=" font-weight-bold pt-4">Create user</h3>
</div>
<br>
<div class="form-group container mb-5">
<form class=" card p-5 z-depth-3" method="post"
style="margin: auto;width: max-content;border-style: double!important;border-color: #fc4c02!important;border-radius: 12px;">
{% csrf_token %}
<div class=" jumbotron-fluid p-4">
<div class="form-group">
<label for="">First Name</label>
{{ form.first_name|as_crispy_field }}
</div>
<div class="form-group">
<label for="">Last Name</label>
{{ form.last_name|as_crispy_field }}
</div>
<div class="form-group">
<label for="">User Name</label>
{{ form.username|as_crispy_field }}
</div>
<div class="form-group">
<label for="">Email</label>
{{ form.email|as_crispy_field }}
</div>
<div class="form-group">
<label for="">Password</label>
{{ form.password1|as_crispy_field }}
<span toggle="#id_password1" class="fa fa-fw fa-eye field-icon1 toggle-password"></span>
</div>
<div class="form-group">
<label for="">Confirm Password</label>
{{ form.password2|as_crispy_field }}
<span toggle="#id_password2" class="fa fa-fw fa-eye field-icon toggle-password"></span>
</div>
</div>
<button class="btn btn-info btn-rounded white-text font-weight-bold wow fadeIn fadeInUp waves-effect waves-light animated"><i class="fas fa-plus-circle mr-2"></i>Create User</button>
</form>
</div>
{% endblock %}
{% block script %}
<script>
$("div #main1").removeClass("container-fluid ").addClass("container");
</script>
<script>
$(".toggle-password").click(function () {
$(this).toggleClass("fa-eye fa-eye-slash");
var input = $($(this).attr("toggle"));
if (input.attr("type") == "password") {
input.attr("type", "text");
} else {
input.attr("type", "password");
}
});
</script>
{% endblock %}
templates/login.html
{% extends 'md-templates/base.html' %}
{% load static %}
{% block title %}
<title>Login</title>
{% endblock %}
{% block body %}
<style>
.login_button {
padding: 0.84rem 2.14rem;
font-size: .81rem;
margin: auto;
padding-top: .7rem;
padding-bottom: .7rem;
background-color: tomato;
color: white;
}
.field-icon {
float: right;
margin-left: -25px;
margin-top: -25px;
margin-right: 10px;
position: relative;
z-index: 2;
}
.container {
padding-top: 50px;
margin: auto;
}
</style>
<style>
.mainForm {
margin-top: 0rem;
padding: 3rem;
}
.imgDiv {
padding-top: 3rem;
}
.leftCol {
padding-left: 3rem;
padding-top: 3rem;
}
.formContainer {
padding: 3rem;
}
@media (max-width: 575.98px) {
.mainForm {
padding: 1rem;
margin-right: 0rem;
}
.leftCol {
display: none;
}
.card {
-webkit-box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0), 0 2px 10px 0 rgba(0, 0, 0, 0);
box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0), 0 2px 10px 0 rgba(0, 0, 0, 0);
background-color: rgba(255, 255, 255, 0);
}
.formContainer {
padding: 1rem;
-webkit-box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12);
box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12);
background-color: #fff;
}
}
@media (min-width: 576px) and (max-width: 767.98px) {
h5 {
font-size: 1rem;
}
.leftCol {
display: none;
}
.card {
-webkit-box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0), 0 2px 10px 0 rgba(0, 0, 0, 0);
box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0), 0 2px 10px 0 rgba(0, 0, 0, 0);
background-color: rgba(255, 255, 255, 0);
}
.formContainer {
padding: 1rem;
-webkit-box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12);
box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12);
background-color: #fff;
}
}
@media only screen and (min-width: 768px) and (max-width: 1024px) {
.mainForm {
padding: 2rem;
}
.leftCol {
padding-left: 0rem;
padding-top: 0rem;
}
.imgDiv {
padding-top: 5rem;
}
.formContainer {
padding-left: 0rem;
}
}
@media only screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) {
.formContainer {
padding: 1rem;
}
.mainForm {
padding: 1rem;
margin-right: 0rem;
}
}
</style>
<div class="container mainForm">
<section>
{% if msg %}
<div class="alert alert-danger alert-dismissible fade show text-center" role="alert">
<strong>{{msg}}</strong>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endif %}
<div class="card mb-4">
<div class="row">
<div class="col-md-6 align-self-center rightCol">
<div class="container formContainer">
<form class="card mainForm" method="post" onsubmit="return validate_form()" id="login_form"
style="">
<p class="h3 text-center mb-4">Sign in</p>
<div class="form-group">
<label for="InputEmail1" class="active"><i
class="fas fa-envelope mr-2"></i>Email</label>
<input type="email" class="form-control" id="InputEmail1" name="InputEmail1"
aria-describedby="emailHelp" placeholder="Enter email">
<span id="email_check_err" style="color:red;"></span>
</div>
<div class="form-group">
<label for="InputPassword1" class="active"><i
class="fas fa-key mr-2"></i>Password</label>
<input class="form-control" id="InputPassword1" type="password" name="InputPassword1"
placeholder="Password">
<span toggle="#InputPassword1"
class="fa fa-fw field-icon toggle-password fa-eye"></span>
<span id="pass_check_err" style="color:red;"></span>
</div>
<div class="form-check">
<input type="checkbox" name="remember_me" id="remember_me" class="form-check-input">
<label for="remember_me" class="form-check-label">Remember Me</label>
</div>
<a class="form-check pt-2" href="{%url 'password_reset' %}" >Forgot your password?</a>
{% csrf_token %}
<button type="submit"
class="btn btn-info btn-rounded white-text font-weight-bold wow fadeIn fadeInUp waves-effect waves-light mt-4">
<i class="fas fa-sign-in-alt pr-2" aria-hidden="true"></i>Login
</button>
</form>
</div>
</div>
</div>
</div>
</section>
</div>
{% endblock %}
{% block script %}
<script>
$(".toggle-password").click(function () {
$(this).toggleClass("fa-eye fa-eye-slash");
var input = $($(this).attr("toggle"));
if (input.attr("type") == "password") {
input.attr("type", "text");
} else {
input.attr("type", "password");
}
});
</script>
<script>
function validate_form()
{
if ($('#InputEmail1').val()=='')
{
//alert('please enter email');
$('#email_check_err').html('*Please Enter Email')
return false;
}
else {
$('#email_check_err').html('')
}
if ($('#InputPassword1').val()=='')
{
//alert('please enter password');
$('#pass_check_err').html('*Please Enter Password')
return false;
}
else {
$('#pass_check_err').html('')
}
}
</script>
<script>
$("nav.navbar").css("position","")
</script>
<script>
//remember me pass owrd for mutliple users start
$('#InputEmail1').change(function(){
//console.log(this.value) //email value
pass = window.localStorage.getItem(this.value);
if(pass != null){ //if there is a password for the meial in input box
$('#InputPassword1').val(JSON.parse(pass));
$('#remember_me').prop('checked', true);
}
});
$(document).submit(function(){
//storing ID password if remember me is checked
if ($('#remember_me').is(':checked')){
const password = document.getElementById('InputPassword1').value;
const email = document.getElementById('InputEmail1').value;
window.localStorage.setItem(email,JSON.stringify(password));
}
});
//remember me pass owrd for mutliple users end
</script>
{% endblock %}
templates/password_reset/password_change.html
{% extends 'templates/base.html' %} {% load crispy_forms_tags %}{% block body %}
<style>
.submit_button {
padding: 0.84rem 2.14rem;
font-size: .81rem;
margin: auto;
padding-top: .7rem;
padding-bottom: .7rem;
background-color: #484749;
color:#d7b261;
}
.container {
padding-top: 50px;
margin: auto;
}
</style>
<div class="text-center">
<h3 class=" font-weight-bold">Change password</h3>
</div>
<br>
<div class="form-group container">
<form class=" card p-5 z-depth-3" method="post"
style="margin: auto;width: max-content;border-style: double!important;border-color: #fc4c02!important;border-radius: 12px;">
{% csrf_token %}
<div class="jumbotron jumbotron-fluid p-4">
<div class="form-group">
{{ form.old_password|as_crispy_field }}
</div>
<div class="form-group">
{{ form.new_password1|as_crispy_field }}
</div>
<div class="form-group">
{{ form.new_password2|as_crispy_field }}
</div>
</div>
<button class="btn btn-sm submit_button">Update Password</button>
</form>
</div>
{% endblock %}
{% block script %}
<script>
$("div #main1").removeClass("container-fluid ").addClass("container");
</script>
{% endblock %}
templates/password_reset/password_reset.html
{% extends 'templates/base.html' %}
{% load static %}
{% block title %}
<title>Reset Confirm</title>
{% endblock %}
{% block body %}
{% load crispy_forms_tags %}
<!--Reset Password-->
<div class="container p-5">
<h2 class="font-weight-bold mt-3">Reset Password</h2>
<hr>
<p>Forgotten your password? Enter your email address below, and we'll email instructions for setting a new one.</p>
<form method="POST" style="width:20%">
{% csrf_token %}
{{ password_reset_form|crispy }}
{% if errors %}
<span style="color: red;font-size:12px;">{{ errors }}</span>
{% endif %}
<button class="btn btn-primary" type="submit">Send email</button>
</form>
</div>
{% endblock %}
{% block script %}
<script type="text/javascript">
function get_ip(json) {
$("#id_location").val(json.ip);
}
</script>
<script src="https://api.ipify.org?format=jsonp&callback=get_ip"></script>
<script>
// Tooltips Initialization
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
</script>
{% endblock %}
templates/password_reset/password_reset_complete.html
{% extends 'templates/base.html' %}
{% load static %}
{% block title %}
<title>Reset complete</title>
{% endblock %}
{% block body %}
<!--Password Reset Complete-->
<div class="container p-4">
<h2 class="font-weight-bold mt-3">Password reset complete</h2>
<hr>
<p>Your password has been set. You may go ahead and log in now.</p>
<a href="{% url 'login' %}" class="btn btn-primary">Log in</a>
</div>
{% endblock %}
{% block script %}
<script type="text/javascript">
function get_ip(json) {
$("#id_location").val(json.ip);
}
</script>
<script src="https://api.ipify.org?format=jsonp&callback=get_ip"></script>
<!-- <script type="text/javascript" src="{% static 'js/jquery.min.js' %}"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> -->
<script>
// Tooltips Initialization
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
</script>
{% endblock %}
templates/password_reset/password_reset_confirm.html
{% extends 'templates/base.html' %}
{% load crispy_forms_tags %}
{% load static %}
{% block title %}
<title>Reset Confirm</title>
{% endblock %}
{% block body %}
<!--Password Reset Confirm-->
<div class="container p-5">
<h2 class="font-weight-bold mt-3">Password Reset Confirm</h2>
<hr>
<p>Please enter your new password.</p>
<form method="POST"><strong>
{% csrf_token %}
{{form}}
</strong>
<div><button class="btn btn-primary" type="submit">Reset password</button></div>
</form>
</div>
{% endblock %}
templates/password_reset/password_reset_done.html
{% extends 'templates/base.html' %}
{% load static %}
{% block title %}
<title>Reset Confirm</title>
{% endblock %}
{% block body %}
<!--Password reset sent-->
<div class="container p-5">
<h2 class="font-weight-bold mt-3">Password reset sent</h2>
<hr>
<p>We've emailed you instructions for setting your password, if an account exists with the email you entered. You should receive them shortly.<br>If you don't receive an email, please make sure you've entered the address you registered with, and check your spam folder.</p>
</div>
{% endblock %}
{% block script %}
<script type="text/javascript">
function get_ip(json) {
$("#id_location").val(json.ip);
}
</script>
<script src="https://api.ipify.org?format=jsonp&callback=get_ip"></script>
<!-- Your custom scripts (optional) -->
<script>
// Tooltips Initialization
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
</script>
{% endblock %}
templates/password_reset/password_reset_email.html
{% autoescape off %}
Hello,
We received a request to reset the password for your account for this email address. To initiate the password reset process for your account, click the link below.
{{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
This link can only be used once. If you need to reset your password again, please visit {{ protocol }}://{{domain}} and request another reset.
If you did not make this request, you can simply ignore this email.
Sincerely,
The QcTitle Team
{% endautoescape %}
How to show a list of users names and reset their password in django views
April 8, 2022, 6:09 p.m.
11how to show a list of users names and reset their password in Django views
urls.py
path('usr', views.Users_list, name='usr'),
path('usr_reset', views.user_password_reset, name='usr_reset'),
views.py
def Users_list(request):
usr = User.objects.objects.all()
# print(usr)
return render(request, 'templates/user_list.html', {'usr': usr})
def user_password_reset(request):
if request.method == 'GET':
usremail = request.GET.get('usremail')
usrpassword = request.GET.get('password')
# print(usremail, usrpassword)
if usrpassword != "":
if usremail != "":
u = User.objects.get(email__exact=usremail)
u.set_password(usrpassword)
u.save()
return HttpResponse('done')
else:
# print('email is empty')
return HttpResponse('failed')
else:
# print('password is empty')
return HttpResponse('failed')
else:
return HttpResponse('failed')
templates/user_list.html
{% extends 'templates/base.html' %}
{% load static %}
{% block body %}
<style>
.field-icon {
float: right;
margin-left: -25px;
margin-top: -28px;
margin-right: 10px;
position: relative;
z-index: 2;
}
.field-icon1 {
float: right;
margin-left: -25px;
margin-top: -28px;
margin-right: 10px;
position: relative;
z-index: 2;
}
table.table-bordered.dataTable tbody td{
vertical-align:middle;
}
</style>
<div id="message"></div>
{# <div class="alert alert-danger alert-dismissible fade show" role="alert">#}
{# <strong>Oo!</strong> #}
{# <button type="button" class="close" data-dismiss="alert" aria-label="Close">#}
{# <span aria-hidden="true">×</span>#}
{# </button>#}
{# </div>#}
<section class="container mt-5">
<div class="card card-cascade narrower z-depth-1">
<div class="table-responsive mt-5" id='thide'>
<div
class="
view view-cascade gradient-card-header blue-gradient-qc narrower py-2 mx-4 mb-3 d-flex justify-content-between align-items-center"
><a href="" class="white-text m-auto">Users List</a>
<div id="example_newSearchPlace"></div>
</div>
<table id="example" class="table table-striped table-bordered table-sm text-justify container" cellspacing="0" width="100%">
<thead>
<tr>
<th>User Name</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for user in usr %}
<tr>
<td>{{ user.username }}</td>
<td>{{ user.first_name }}</td>
<td>{{ user.last_name }}</td>
<td>{{ user.email }}</td>
<td align="center">
<button type="button" class="btn btn-info btn-rounded white-text font-weight-bold wow fadeIn fadeInUp waves-effect waves-light m-auto" data-toggle="modal"
data-target="#exampleModal{{ user.id }}">
<i class="fas fa-user-cog mr-2"></i>Reset Password
</button>
</td>
</tr>
<!-- Modal -->
<div class="modal fade" id="exampleModal{{ user.id }}" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content" style="border:1px solid tomato">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Reset password For
: {{ user.email }}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="password{{ user.id }}" class="col-form-label">Password:</label>
<input type="password" class="form-control" name="password{{ user.id }}"
id="password{{ user.id }}"
placeholder="password">
<span toggle="#password{{ user.id }}"
class="fa fa-fw fa-eye field-icon toggle-password"></span>
</div>
<small id="hint_id_new_password1" class="form-text text-muted">
<ul>
<li>Your password can’t be too similar to your other personal
information.
</li>
<li>Your password must contain at least 8 characters.</li>
<li>Your password can’t be a commonly used password.</li>
<li>Your password can’t be entirely numeric.</li>
</ul>
</small>
<div class="form-group">
<label for="repassword{{ user.id }}"
class="col-form-label">Re-Password:</label>
<input type="password" class="form-control" name="repassword{{ user.id }}"
id="repassword{{ user.id }}"
placeholder="repassword">
<span toggle="#repassword{{ user.id }}"
class="fa fa-fw fa-eye field-icon1 toggle-password"></span>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info btn-rounded white-text font-weight-bold wow fadeIn fadeInUp waves-effect waves-light m-auto" data-dismiss="modal"><i class="far fa-window-close mr-2"></i>Close</button>
<button type="button" class="btn btn-info btn-rounded white-text font-weight-bold wow fadeIn fadeInUp waves-effect waves-light m-auto"
onclick="return rest_usr('{{ user.email }}','{{ user.id }}')">Save changes
</button>
</div>
</div>
</div>
</div>
{% endfor %}
</tbody>
</table>
</div>
</div>
</section>
{% endblock %}
{% block script %}
<script type="text/javascript">
/* function mytable() {
$('#example').DataTable({
dom: 'Blfrtip',
buttons: [],
{#pageLength: 10,#}
lengthMenu: [
[5, 10, 25, 50, -1],
[5, 10, 25, 50, 'All'],
],
iDisplayLength: -1,
});
$('.dataTables_length').addClass('bs-select');
$('#example').on('draw.dt', function () {
//This will get called when data table data gets redrawn to the table.
status_count();
});
} */
function mytable() {
var table6 = $("#example").DataTable({
dom: "lfrtip",
"order": [],
"aaSorting": [],
lengthChange: false,
pageLength: 25,
lengthMenu: [
[5, 10, 25, 50, -1],
[5, 10, 25, 50, "All"],
],
scrollX: true,
scrollY: "50vh",
scrollCollapse: true,
language: {
search: "_INPUT_", // Removes the 'Search' field label
searchPlaceholder: "Search", // Placeholder for the search box
},
fnInitComplete: function () {
$("div.toolbar").html("Custom tool bar!");
},
//'order': [1, 'asc'],
});
$(".side_by_side_hide").css("display","none");
$(".dataTables_length").addClass("bs-select");
table6.buttons().container().appendTo($("#example_test"));
// search box custom class
$(".dataTables_filter").toggleClass(
"dataTables_filter dataTables_filter"
);
$("#example_newSearchPlace").html($(".dataTables_filter"));
$('#thide').css("padding",'20px')
}
</script>
<script type="text/javascript">
$(document).ready(function () {
mytable();
});
</script>
<script>
function rest_usr(email, id) {
var password = $('#password' + id).val();
var repassword = $('#repassword' + id).val();
if (password === '') {
alert("Pls enter password");
return false;
}
if (repassword === '') {
alert("Pls enter repassword");
return false;
}
if (repassword !== password) {
alert("password don't match");
return false;
} else {
var lowerCaseLetters = /[a-z]/g;
if (password.match(lowerCaseLetters)) {
} else {
alert('Your password must contain at least one small letter')
return false;
}
var upperCaseLetters = /[A-Z]/g;
if (password.match(upperCaseLetters)) {
} else {
alert('Your password must contain at least one capital letter');
return false;
}
var numbers = /[0-9]/g;
if (password.match(numbers)) {
} else {
alert('Your password must contain at least one number')
return false;
}
if (password.length < 8) {
alert('Your password must contain at least 8 characters')
return false
}
}
if (email === '') {
alert('pls enter email');
return false;
}
// serialize the data for sending the form data.
var usremail = email;
// make POST ajax call
$.ajax({
type: 'GET',
url: '{% url "usr_reset" %}',
data: {usremail: usremail, password: password},
success: function (data) {
if (data == 'done') {
$('#exampleModal' + id).modal('hide');
$('#password' + id).val('');
$('#repassword' + id).val('');
$('#message').val('password updated successfully');
}
if (data == 'failed') {
$('#message').val('unable to reset password');
}
}
})
}
</script>
<script>
$(".toggle-password").click(function () {
$(this).toggleClass("fa-eye fa-eye-slash");
var input = $($(this).attr("toggle"));
if (input.attr("type") == "password") {
input.attr("type", "text");
} else {
input.attr("type", "password");
}
});
</script>
{% endblock %}
Aws s3 bucket folder structure in django
April 8, 2022, 5:15 p.m.
10AWS S3 Bucket folder structure in Django
in this tutorial we will open files from the s3 bucket and download the file to our system
urls.py
path("s3_files", views.s3_download, name="s3-bucket"),
views.py
import boto3
from botocore.client import Config
from botocore.exceptions import ClientError
import re
# python > 3 should be installed
# pip install boto3
# s3v4
# (Default) Signature Version 4
# v4 algorithm starts with X-Amz-Algorithm
#
# s3
# (Deprecated) Signature Version 2, this only works in some regions new regions not supported
# if you have to generate signed url that has > 7 days expiry then use version 2 if your region supports it
s3_signature = {
'v4': 's3v4',
'v2': 's3'
}
AWS_ACCESS_KEY_ID = settings.AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY = settings.AWS_SECRET_ACCESS_KEY
AWS_DEFAULT_REGION = 'us-east-1'
# Bucket_name = 'eigen.loc'
# filename = "V3547D335"
def create_presigned_url(bucket_name, bucket_key, expiration=3600, signature_version=s3_signature['v4']):
"""Generate a presigned URL for the S3 object
:param bucket_name: string
:param bucket_key: string
:param expiration: Time in seconds for the presigned URL to remain valid
:param signature_version: string
:return: Presigned URL as string. If error, returns None.
"""
s3_client = boto3.client('s3',
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
config=Config(
signature_version=signature_version),
region_name=AWS_DEFAULT_REGION
)
try:
response = s3_client.generate_presigned_url('get_object',
Params={'Bucket': bucket_name,
'Key': bucket_key},
ExpiresIn=expiration)
# print('buket_owner=', s3_client.list_buckets()['Owner'])
# for key in s3_client.list_objects(Bucket=bucket_name, Prefix=bucket_key)['Contents']:
# print('key_value=', key['Key'])
except ClientError as e:
logging.error(e)
return None
# The response contains the presigned URL
return response
def s3_download(request):
#intitializing variables ,libs and sessions
import boto3
session = boto3.Session(
aws_access_key_id=Your_AWS_ACCESS_KEY_ID,
aws_secret_access_key=Your_AWS_SECRET_ACCESS_KEY )
#Then use the session to get the resource
s3 = session.resource('s3')
my_bucket = s3.Bucket('YourBucketname')
set_folder = []
urls = []
x=[]
# when the function is called >1 times with a folder name recieved in get request ->(folder to go to, previous directories)
if request.method == "GET":
folder = list(request.GET.items())
# print(folder)
if folder:
# print("in get")
# folder_prefix = folder[0][0]
# adding previous directory and the current directory to go to
urls = [folder[0][1]+ folder[0][0]]
# split_times = folder[0][1].count("/")
split_times = urls[0].count("/")
# print(split_times)
# removing / from the beiginning and searching for the above urls's folder and files
for obj in my_bucket.objects.filter(Prefix=urls[0].lstrip("/")):
# print(obj.key)
x.append(str(obj.key))
# print(x)
# if / in urls variable and / in recieved objects are not equal its a folder or it is a file
folder_name = map(lambda x : x.split("/")[split_times-1] + "/" if (x. count("/")!=split_times-1) else x,x)
folder_name = set(folder_name)
# print(folder_name)
for folder in folder_name:
if folder.endswith("/"):
set_folder.append([folder,None])
else:
# generating link for the file and sending to template
set_folder.append([folder.split("/")[-1],create_presigned_url("YourBucketName",folder,604800)])
print(set_folder,urls)
return render(request,"templates/sub_folder.html",{"files":set_folder,"folder_url":urls})
# when the function is called the first time to retrieve the files and folders in the s3 bucket
for my_bucket_object in my_bucket.objects.all():
# print(my_bucket_object.key)
# adding all files names to an array
x.append(str(my_bucket_object.key))
# splitting the file and getting the main folder or file
folder_name = map(lambda x : x.split("/")[0] + "/" if (x.count("/")>0) else x,x)
# folder_name = map(check_folder,x)
# print(folder_name)
# removing redundant folder_names
folder_name = set(folder_name)
for folder in folder_name:
if "/" in folder:
set_folder.append([folder,None])
else:
# adding a presigned url for download valid for 5mins if it is a file and sending the data to template
set_folder.append([folder,create_presigned_url("YourBucketName",folder,604800)])
urls = ["/"]
# print(set_folder)
return render(request,"templates/sub_folder.html",{"files":set_folder,"folder_url":urls})
templates/sub_folder.html
{% extends 'templates/base.html' %} {% load static %}
{% block title %}
<title>LOC Files</title>
{% endblock %}
{% block body %}
<style>
table.table th, table.table td {
text-align:center;
}
/* table { */
/* table-layout: fixed; */
/* border-collapse: collapse; */
/* } */
/* tr td:nth-child(3) {
overflow: hidden;
white-space: nowrap;
} */
.btn_view{
width: 140px;
height: 38px;
text-align:center;
line-height:1.1em;
min-width:120px;
}
.modal-body{
max-height:400px;
overflow-y: auto;
}
</style>
<section class="container mt-5">
<!-- bredcrums -->
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="{% url 's3-bucket' %}">Back to main Folder</a></li>
</ol>
</nav>
<!-- Panel -->
<div class="card mb-lg-0 mb-4">
<div class="card-header white-text primary-color text-center">
<h5 class="font-weight-500 my-1">Files
</h5>
</div>
<div class="card-body">
<form method="GET" class="text-center" style="color: #757575;">
<div class="table-responsive">
<div id="example7_wrapper" class="dataTables_wrapper dt-bootstrap4 no-footer">
<div class="dt-buttons"></div>
<table class="table table-striped table-bordered table-sm dataTable no-footer" cellspacing="0" width="100%" id="example7" role="grid" aria-describedby="example7_info" style="width: 100%;">
<thead>
<tr role="row">
<th class="font-weight-bold sorting" tabindex="0" aria-controls="example7" rowspan="1" colspan="1" aria-label="Status: activate to sort column ascending" style="width: 44.2px;">Files</th>
<th class="font-weight-bold sorting" tabindex="0" aria-controls="example7" rowspan="1" colspan="1" aria-label="File Name: activate to sort column ascending" style="width: 77.2px;">File Name</th>
<th class="font-weight-bold sorting" tabindex="0" aria-controls="example7" rowspan="1" colspan="1" aria-label="Action: activate to sort column ascending" style="width: 133.2px;">Action</th>
</tr>
</thead>
<tbody>
{% for file in files %}
<tr role="row" class="odd align-middle">
<td class="align-middle">
{% if ".xlsx" in file.1 %}
<i class="far fa-file-excel fa-lg text-primary"></i>
{% elif ".docx" in file.1 %}
<i class="far fa-file-word fa-lg text-success"></i>
{% elif ".txt" in file.1 %}
<i class="far fa-file-alt fa-lg"></i>
{% elif ".pdf" in file.1 %}
<i class="far fa-file-pdf fa-lg text-danger"></i>
{%else%}
<i class="fas fa-folder fa-lg text-warning"></i>
{% endif %}
</td>
<td class="align-middle"> {{ file.0 }}</td>
<td class="text-center align-middle">
{% if file.1 %}
<a href="{{ file.1 }}" class="folder_redirect btn btn-sm" download="{{ file.0}}"><i class="fas fa-file-download"></i>Download</a>
{% else %}
<button type="submit" name="{{ file.0 }}" value = "{{folder_url.0}}" class="folder_redirect btn btn-sm" >go to folder</button>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</form>
</div>
</div>
<!-- Panel -->
</section>
{% endblock %}
{% block script %}
{% endblock %}
Django ngnix gunicorn troubleshoot
March 28, 2022, 10:08 p.m.
31Django Nginx Gunicorn troubleshoot
504 Gateway Timeout:
---------------------
Gunicorn — By default the Gunicorn timeout is 30 sec. For increase the timeout in Gunicorn upto 5 min (300 sec) we need to update ExecStart in Gunicorn configuration file.
sudo vim /etc/systemd/system/gunicorn.service
[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/projects/your_project_name
ExecStart=/home/ubuntu/projects/env-myproject/bin/gunicorn --access-logfile - --workers 3 --timeout 1800 --bind unix:/home/ubuntu/projects/your_project_name.sock your_project_name.wsgi:application
[Install]
WantedBy=multi-user.target
press esc
:wq+ enter
If you decide to make changes to the gunicorn systemd service file, make sure you reload the daemon and restart gunicorn
sudo systemctl daemon-reload
sudo systemctl restart gunicorn
sudo systemctl status gunicorn
-----------------------------------------------
Nginx — By default the Nginx timeout is 60 sec. For increase the timeout in Nginx upto 5 min (300 sec) add following parameters in proxy_params.
sudo vim /etc/nginx/proxy_params
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 300;
proxy_send_timeout 300;
proxy_read_timeout 300;
client_max_body_size 50M;
press esc
:wq+ enter
When you make changes to the Nginx server block configuration test the config
sudo nginx -t && sudo systemctl restart nginx
================================================================================================
Further Troubleshooting:-
-----------------------
For additional troubleshooting, the logs can help narrow down root causes. Check each of them in turn and look for messages indicating problem areas.
The following logs may be helpful:
Check the Nginx process logs by typing:
sudo journalctl -u nginx
Check the Nginx access logs by typing:
sudo less /var/log/nginx/access.log
Check the Nginx error logs by typing:
sudo less /var/log/nginx/error.log
Check the Gunicorn application logs by typing:
sudo journalctl -u gunicorn
Check the Gunicorn socket logs by typing:
sudo journalctl -u gunicorn.socket
As you update your configuration or application, you will likely need to restart the processes to adjust to your changes.
If you update your Django application, you can restart the Gunicorn process to pick up the changes by typing:
sudo systemctl restart gunicorn
If you change Gunicorn socket or service files, reload the daemon and restart the process by typing:
sudo systemctl daemon-reload
sudo systemctl restart gunicorn.socket gunicorn.service
If you change the Nginx server block configuration, test the configuration and then Nginx by typing:
sudo nginx -t && sudo systemctl restart nginx
Ref links:
https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04
https://www.datadoghq.com/blog/nginx-502-bad-gateway-errors-gunicorn/#:~:text=Gunicorn%20is%20a%20popular%20application%20server%20for%20Python%20applications.&text=NGINX%20proxies%20web%20requests%20and,if%20Gunicorn%20fails%20to%20respond.
https://www.journaldev.com/28002/django-postgres-nginx-gunicorn-ubuntu
https://docs.gunicorn.org/en/0.17.2/configure.html
Django sites available for nginx
March 28, 2022, 10:05 p.m.
20Django sites available for Nginx
server {
listen 80; #port number
server_name your_server_ip_address www.yourwebsitename.com yourwebsite; #server ip address or domain name
location = /favicon.ico { access_log off; log_not_found off; } #favicon location
location /static/ {
root /home/project/your_project_name; #static files for project location
}
location / {
include proxy_params;
proxy_pass http://unix:/home/project/your_project_name.sock; # project socket connection location path
proxy_connect_timeout 900; # connection time out
proxy_send_timeout 900; # file send time out
proxy_read_timeout 900; # file read time out
fastcgi_send_timeout 900; # time taken to send request
fastcgi_read_timeout 900; # time taken to read request
client_max_body_size 50M; # client max file size upload
}
}
How to enable cors headers in your django for api
Feb. 9, 2022, 10:59 p.m.
185How to enable CORS headers in your Django for api
When site A wants to access content from another site B, it is called a Cross-Origin request. As it is disabled for security reasons, B sends an Access-Control-Allow-Origin header in the response. By default, a domain is not allowed to access an API hosted on another domain. If we want to allow our REST API (say backend) hosted in our Django application to be accessed from other applications (say front-end) hosted on another server, we must enable CORS (Cross-Origin Resource Sharing).
Steps to allow CORS in your Django Project –
1. Install django-cors-headers using PIP:
pip install django-cors-headers
2.Add cors headers to the installed applications section in the settings.py file:
INSTALLED_APPS = [
...
'corsheaders',# add this
...
]
3. Add corsheaders.middleware.CorsMiddleware to middleware section in settings.py file:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
...
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware', # add this
]
4. If you want to allow access for all domains, set the following variable to TRUE in settings.py file:
CORS_ORIGIN_ALLOW_ALL = True
Alternatively, you can specify which domains you want to give access to by doing the following in settings.py file:
#CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOWED_ORIGINS = [
"http://www.kwikl3arn.com",
"http://kwikl3arn.com",
]
That’s all! Now your API is accessible to other applications hosted on other selected servers.
How to add a free ssl certificate in ngnix for django
Jan. 5, 2022, 12:50 a.m.
146How to add a free SSL certificate in Nginx for Django
Download the Let’s Encrypt Client: For Ubuntu 18.04 and later, substitute the Python 3 version
apt-get update
sudo apt-get install certbot
apt-get install python3-certbot-nginx
to make sure that our Nginx configuration is correctly set. The certbot program directly reads and writes into the Nginx file.
The important setup that we need to make is sure to have server_name is set to the domain name.
Open the Nginx configuration file using nano editor:
sudo nano /etc/nginx/sites-available/your_app_name
server {
listen 80; #L1
server_name 5.xx.x8x.x9 beta.kwikl3arn.com www.beta.kwikl3arn.com; #L2
location = /favicon.ico { access_log off; log_not_found off; } #L3
location /static/ { #L4
root /home/project/kwikl3arn;
}
location / { #l5
include proxy_params;
proxy_pass http://unix:/home/project/kwikl3arn.sock;
proxy_connect_timeout 900;
proxy_send_timeout 900;
proxy_read_timeout 900;
fastcgi_send_timeout 900;
fastcgi_read_timeout 900;
client_max_body_size 100M;
}
}
Check if the server_name is set with your domain address. In my setup, it should be:
server_name beta.kwikl3arn.com
If you’ve made the changes to reflect server name to your domain address, then test the configuration file using the below command:
sudo nginx -t
If everything looks OK, then restart the Nginx using the below command to commit the changes on the server.
sudo service restart nginx
Install Certbot for Let’s Encrypt
Now that we are all good with Nginx, let’s start installing the LetEncrypt certificate on the server. As I mentioned, we will be using the Certbot program to manage the free SSL encryption.
Let’s start off with updating the repository and installing the pre-requisite software.
sudo apt-get update
sudo apt-get install software-properties-common
sudo add-apt-repository universe
Once the installation is completed, run the below command to generate the certificate. This will also modify the Nginx blocks configuration file to enable the HTTP to HTTPS redirection along with updating live certificate locations.
sudo certbot – nginx -d kwikl3arn.com -d www.kwikl3arn.com # these are already taken
In my case, I will be installing a certificate only at beta.kwikl3arn.com.
sudo certbot – nginx -d beta.kwikl3arn.com
You’ll be prompted to enter a few details while generating the certificate specific to your domain name.
In the process, you will be also asked how to manage the HTTP traffic and provided with two options.
- No redirect – Make no further changes to the webserver configuration.
- Redirect – Make all requests redirect to secure HTTPS access.
You should choose the second option to make the website or blog more secure and redirect HTTP traffic to HTTPS in order to avoid the duplicate content issue as HTTP & HTTPS versions.
Renew LetsEncrypt Certificate for Nginx
Method 1:
Let’s Encrypt certificate issued for 90 days only. If we do not renew the certificate, it gets expired post 90 days. But thankfully, the certbot program has the ability to automatically renew the SSL certificate 30 days prior to expiration.
You can also check the validity of the certificate by hitting on the padlock on the domain name and select the certificate.
When certbot is being installed, it also adds a rule into CRON jobs to check the certificate validity daily.
We can check whether certificates need renewal by hitting the dry run command.
sudo certbot renew – dry-run
This command will just stimulate the certificate renewal, however, do not update the existing certificates.
If you want to renew the certificate immediately, you can run the following command without dry run :
sudo certbot renew
You can also view the installed certificates for all the domains on your server using the below command:
sudo certbot certificates
Method 2:
-
Open the crontab file.
crontab -e
-
Add the
certbot
command to run daily. In this example, we run the command every day at noon. The command checks to see if the certificate on the server will expire within the next 30 days, and renews it if so. The--quiet
directive tellscertbot
not to generate output.0 12 * * * /usr/bin/certbot renew --quiet
-
Save and close the file. All installed certificates will be automatically renewed and reloaded.
Ref:
https://www.nginx.com/blog/using-free-ssltls-certificates-from-lets-encrypt-with-nginx/
https://restorebin.com/letsencrypt-nginx-certbot/
https://www.codechannel.xyz/blog/2020-06-14-config-nginx-certbot-static-files.html
Dynamic navigation menu based on the user in django
Dec. 15, 2021, 1:43 a.m.
209Dynamic navigation menu based on the user in Django
Entire app source code is given below
https://github.com/kwikl3arn/dynamic_navigation_menu_django
Dynamic_app/models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class main_menu(models.Model):
m_menu_id = models.AutoField(primary_key=True)
m_menu_name = models.CharField(max_length=50)
m_menu_link = models.CharField(max_length=100, blank=True, null=True)
class sub_menu(models.Model):
s_menu_id = models.AutoField(primary_key=True)
m_menu_id = models.IntegerField()
s_menu_name = models.CharField(max_length=50)
s_menu_link = models.CharField(max_length=100, blank=True, null=True)
class user_role(models.Model):
Role_name = models.CharField(blank=True, null=True, max_length=50)
role_status = models.BooleanField(default=True)
class main_menu_permission(models.Model):
m_menu_id = models.IntegerField()
m_menu_name = models.CharField(max_length=50, blank=True, null=True)
m_menu_link = models.CharField(max_length=100, blank=True, null=True)
role_id = models.IntegerField()
user_id=models.CharField(max_length=50, blank=True, null=True)
class sub_menu_permission(models.Model):
s_menu_id = models.IntegerField()
m_menu_id = models.IntegerField()
s_menu_name = models.CharField(max_length=50, blank=True, null=True)
s_menu_link = models.CharField(max_length=100, blank=True, null=True)
role_id = models.IntegerField()
user_id = models.CharField(max_length=50, blank=True, null=True)
Dynamic_app/views.py
from django.shortcuts import render, redirect
from django.contrib import auth
from django.contrib.auth import authenticate
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from dynamic_app.models import *
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout, get_user_model
from django.conf import settings
# Create your views here.
# login validation view
def login_page(request):
# print('--------------------------------------')
# print('now in login_page')
if request.user.is_authenticated:
return redirect(settings.LOGIN_REDIRECT_URL)
elif request.method == "POST":
# print(request.POST)
username = request.POST.get('InputEmail1')
password = request.POST.get('InputPassword1')
user = authenticate(request, username=username, password=password)
if user is None:
User = get_user_model()
user_queryset = User.objects.all().filter(email__iexact=username)
if user_queryset:
username = user_queryset[0].username
user = authenticate(username=username, password=password)
if user is not None:
request.session.set_expiry(14400) # session expire in 4 hrs
login(request, user) # the user is now logged in
# print('user loged in:', request.user.is_authenticated)
# if user clicked something which is required login,
# after login it will redirect to that page,what ever user clicked
if 'next' in request.GET:
return redirect(request.GET['next'])
else:
return redirect('dmenu')
else:
return render(request, 'login.html', context={'msg': 'Invalid User Name / Password'})
else:
return render(request, 'login.html', context={})
def menu_all_data(uid):
print('uid=',uid)
menu = main_menu_permission.objects.filter(user_id=uid)
submenu = sub_menu_permission.objects.filter(user_id=uid)
return [menu,submenu]
# logout view
@login_required
def logout_view(request):
# print('--------------------------------------')
# print('now in logout_view')
logout(request)
return redirect('login')
def maninmenu(request):
mainmenu = main_menu.objects.all()
menu,submenu = menu_all_data(request.user.id)
return render(request, 'menu.html', {'main_menu': mainmenu,'menu': menu, 'submenu': submenu})
def submenu(request):
m_menu = main_menu.objects.all()
s_submenu = sub_menu.objects.all()
menu,submenu = menu_all_data(request.user.id)
return render(request, 'submenu.html', {'m_menu': m_menu, 's_submenu': s_submenu,'menu': menu, 'submenu': submenu})
def mainsave(request):
if request.method == 'POST':
mname = request.POST['menu_name']
mlink = request.POST['mn_link']
main_menu.objects.create(m_menu_name=mname, m_menu_link=mlink)
# return HttpResponse("created")
return redirect('mainmenu')
else:
return redirect('mainmenu')
def subsave(request):
if request.method == 'POST':
menuid = request.POST['parent']
sname = request.POST['sub_menu_name']
slink = request.POST['sub_menu_link']
sub_menu.objects.create(m_menu_id=menuid, s_menu_name=sname, s_menu_link=slink)
return redirect('submenu')
else:
return redirect('submenu')
@login_required()
def dynamic_menu(request):
menu = main_menu_permission.objects.filter(user_id=request.user.id)
submenu = sub_menu_permission.objects.filter(user_id=request.user.id)
# print(request.user.id,request.user)
return render(request, 'dynamic_menu.html', {'menu': menu, 'submenu': submenu})
def userroles(request):
usrrole = user_role.objects.all()
menu,submenu = menu_all_data(request.user.id)
return render(request, 'user_role.html', {'usr_role': usrrole,'menu': menu, 'submenu': submenu})
def userroles_save(request):
if request.method == 'POST':
rolename = request.POST['Role_name']
user_role.objects.create(Role_name=rolename)
return redirect('role')
else:
return redirect('role')
def user_role_menu(request):
r_menu = main_menu.objects.all()
r_submenu = sub_menu.objects.all()
r_usrrole = user_role.objects.all()
user = User.objects.all()
menu,submenu = menu_all_data(request.user.id)
return render(request, 'user_role_menu.html', {'r_menu': r_menu, 'r_submenu': r_submenu, 'r_usrrole': r_usrrole, 'user': user,'menu': menu, 'submenu': submenu})
def user_role_menu_save(request):
if request.method == 'POST':
rolename = request.POST['Role_name']
username = request.POST['user_name']
print(rolename,username)
menu = request.POST.getlist('menu[]')
main_menu_permission.objects.filter(user_id=username).delete()
sub_menu_permission.objects.filter(user_id=username).delete()
for m in menu:
submenu = request.POST.getlist('submenu_{}[]'.format(m))
menu = main_menu.objects.filter(m_menu_id=m)
print('menu=', menu[0].m_menu_name)
main_menu_permission.objects.create(m_menu_id=m, m_menu_name=menu[0].m_menu_name,
m_menu_link=menu[0].m_menu_link, role_id=rolename, user_id=username)
for sub in submenu:
# print('sub=', sub)
subm = sub_menu.objects.filter(s_menu_id=sub)
print('submenu=', subm[0].s_menu_name)
sub_menu_permission.objects.create(s_menu_id=sub, m_menu_id=m, s_menu_name=subm[0].s_menu_name,
s_menu_link=subm[0].s_menu_link, role_id=rolename, user_id=username)
return redirect('user_role_menu')
else:
pass
def user_role_menu_edit(request):
if request.method == 'GET':
userid=request.GET.get('username')
# print('userid=',userid,request.GET.getlist('username'))
r_menu = main_menu.objects.all()
r_usrrole = user_role.objects.all()
user = User.objects.all()
menu,submenu = menu_all_data(userid)
user_checked=[]
for subm in submenu:
user_checked.append(subm.s_menu_id)
from django.db.models import Q
r_submenu = sub_menu.objects.filter(~Q(s_menu_id__in=user_checked))
return render(request, 'user_role_menu1.html', {'r_menu': r_menu, 'r_submenu': r_submenu, 'r_usrrole': r_usrrole, 'user': user,'menu': menu, 'submenu': submenu})
Dynamic_app/nav_context_processesor.py
from .models import main_menu_permission, sub_menu_permission
def nav_render(request):
menu = main_menu_permission.objects.filter(user_id=request.user.id)
submenu = sub_menu_permission.objects.filter(user_id=request.user.id)
# print(request.user.id,request.user)
return {'menu1': menu, 'submenu1': submenu}
dynamicmenu/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'dynamic_app.apps.DynamicAppConfig',#add your app name
]
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',
'dynamic_app.nav_context_processesor.nav_render' #add this
],
},
},
]
LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'dmenu'
dynamicmenu/urls.py
from django.contrib import admin
from django.urls import path
from dynamic_app import views
urlpatterns = [
path('admin/', admin.site.urls),
path('main', views.maninmenu, name='mainmenu'),
path('submenu', views.submenu, name='submenu'),
path('mainsave', views.mainsave, name='msave'),
path('submenusave', views.subsave, name='submenusave'),
path('role', views.userroles, name='role'),
path('userroles_save', views.userroles_save, name='userroles_save'),
path('user_role_menu', views.user_role_menu, name='user_role_menu'),
path('user_role_menu_save', views.user_role_menu_save, name='user_role_menu_save'),
path('user_role_menu_edit', views.user_role_menu_edit, name='user_role_menu_edit'),
path('', views.dynamic_menu, name='dmenu'),
path('login', views.login_page, name='login'),
path('logout', views.logout_view, name='logout'),
]
templates/base.html
{% load static %}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="icon" href="{% static 'img/mdb-favicon.ico' %}" type="image/x-icon">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css">
<!-- Google Fonts Roboto -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<!-- Material Design Bootstrap -->
<link rel="stylesheet" href="{% static 'css/mdb.min.css' %}">
<!-- Your custom styles (optional) -->
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<style>
.double-nav .breadcrumb-dn {
color: #fff;
}
.side-nav.wide.slim .sn-ad-avatar-wrapper a span {
display: none;
}
</style>
{% block title %}
{% endblock %}
</head>
<body class="fixed-sn mdb-skin">
<!--Double navigation-->
<header>
<!-- Sidebar navigation -->
<div id="slide-out" class="side-nav sn-bg-4 fixed">
<ul class="custom-scrollbar">
<!-- Logo -->
<li>
<div class="logo-wrapper waves-light">
<a href="#"><img src="https://mdbootstrap.com/img/logo/mdb-transparent.png" class="img-fluid flex-center"></a>
</div>
</li>
<!--/. Logo -->
<!-- Side navigation links -->
<li>
<ul class="collapsible collapsible-accordion">
{% for m in menu1 %}
<li><a class="collapsible-header waves-effect arrow-r"><i
class="sv-slim-icon far fa-hand-point-right"></i> {{ m.m_menu_name }}<i
class="fas fa-angle-down rotate-icon"></i></a>
<div class="collapsible-body">
<ul>
{% for s in submenu1 %}
{% if m.m_menu_id == s.m_menu_id %}
<li><a href="{{ s.s_menu_link }}" class="waves-effect">
<span class="sv-normal">{{ s.s_menu_name }}</span></a></li>
{% endif %}
{% endfor %}
</ul>
</div>
</li>
{% endfor %}
</ul>
</li>
<!--/. Side navigation links -->
</ul>
<div class="sidenav-bg mask-strong"></div>
</div>
<!--/. Sidebar navigation -->
<!-- Navbar -->
<nav class="navbar fixed-top navbar-toggleable-md navbar-expand-lg scrolling-navbar double-nav">
<!-- SideNav slide-out button -->
<div class="float-left">
<a href="#" data-activates="slide-out" class="button-collapse"><i class="fas fa-bars"></i></a>
</div>
<!-- Breadcrumb-->
<div class="breadcrumb-dn mr-auto">
<p>Material Design for Bootstrap</p>
</div>
<ul class="nav navbar-nav nav-flex-icons ml-auto">
<li class="nav-item">
<a class="nav-link"><i class="fas fa-envelope"></i> <span class="clearfix d-none d-sm-inline-block">Contact</span></a>
</li>
<li class="nav-item">
<a class="nav-link"><i class="fas fa-comments"></i> <span class="clearfix d-none d-sm-inline-block">Support</span></a>
</li>
{% if request.user.is_authenticated %}
<li class="nav-item">
<a class="nav-link"><i class="fas fa-user"></i> <span
class="clearfix d-none d-sm-inline-block">{{request.user.username}}</span></a>
</li>
<li class="nav-item dropdown">
<a class="nav-link" href="{% url 'logout' %}"><i class="fas fa-power-off " data-toggle="tooltip" data-placement="bottom" title="Logout"></i></a>
</li>
{% else %}
<li class="nav-item dropdown">
<a class="nav-link" href="{% url 'login' %}">Login</a>
</li>
{% endif %}
</ul>
</nav>
<!-- /.Navbar -->
</header>
<!--/.Double navigation-->
<!--Main Layout-->
<main>
<div class="container-fluid mt-5">
{% block body %}
{% endblock %}
</div>
</main>
<!--Main Layout-->
<!-- jQuery -->
<script type="text/javascript" src="{% static 'js/jquery.min.js' %}"></script>
<!-- Bootstrap tooltips -->
<script type="text/javascript" src="{% static 'js/popper.min.js' %}"></script>
<!-- Bootstrap core JavaScript -->
<script type="text/javascript" src="{% static 'js/bootstrap.min.js' %}"></script>
<!-- MDB core JavaScript -->
<script type="text/javascript" src="{% static 'js/mdb.min.js' %}"></script>
<!-- Your custom scripts (optional) -->
{# <script type="text/javascript"></script>#}
<script>
$(document).ready(function() {
// SideNav Initialization
$(".button-collapse").sideNav();
new WOW().init();
})
</script>
{% block script %}
{% endblock %}
</body>
</html>
templates/dynamic_menu.html
{% extends 'base.html' %}
{% for m in menu1 %}
<li><a class="collapsible-header waves-effect arrow-r"><i
class="sv-slim-icon far fa-hand-point-right"></i> {{ m.m_menu_name }}<i
class="fas fa-angle-down rotate-icon"></i></a>
<div class="collapsible-body">
<ul>
{% for s in submenu1 %}
{% if m.m_menu_id == s.m_menu_id %}
<li><a href="{{ s.s_menu_link }}" class="waves-effect">
<span class="sv-slim"> {{ s.s_menu_name }} </span>
<span class="sv-normal">{{ s.s_menu_name }}</span></a></li>
{% endif %}
{% endfor %}
</ul>
</div>
</li>
{% endfor %}
templates/login.html
{% extends 'base.html' %}
{% load static %}
{% block title %}
<title>Quality Control Application for Titles</title>
{% endblock %}
{% block body %}
<style>
.login_button {
padding: 0.84rem 2.14rem;
font-size: .81rem;
margin: auto;
padding-top: .7rem;
padding-bottom: .7rem;
background-color: tomato;
color: white;
}
.field-icon {
float: right;
margin-left: -25px;
margin-top: -25px;
margin-right: 10px;
position: relative;
z-index: 2;
}
.container {
padding-top: 50px;
margin: auto;
}
</style>
<div class="container p-5">
{% if msg %}
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<strong>Oo!</strong> {{ msg }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endif %}
<form class=" card p-5 z-depth-3" method="post" onsubmit="return validate_form()"
style="margin: auto;width: max-content;border-style: double!important;border-color: #fc4c02!important;border-radius: 12px;">
<p class="h3 text-center mb-4">Sign in</p>
<div class="form-group">
<label for="InputEmail1">Email address</label>
<input type="email" class="form-control" id="InputEmail1" name="InputEmail1"
aria-describedby="emailHelp"
placeholder="Enter email">
{#<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>#}
</div>
<div class="form-group">
<label for="InputPassword1">Password</label>
<input class="form-control" id="InputPassword1" type="password" name="InputPassword1"
placeholder="Password">
<span toggle="#InputPassword1" class="fa fa-fw fa-eye field-icon toggle-password"></span>
</div>
{% csrf_token %}
<button type="submit" class="btn login_button my-4">
Submit
</button>
</form>
</div>
{% endblock %}
{% block script %}
<script>
$(".toggle-password").click(function () {
$(this).toggleClass("fa-eye fa-eye-slash");
var input = $($(this).attr("toggle"));
if (input.attr("type") == "password") {
input.attr("type", "text");
} else {
input.attr("type", "password");
}
});
</script>
<script>
function validate_form()
{
if ($('#InputEmail1').val()=='')
{
alert('please enter email');
return false;
}
if ($('#InputPassword1').val()=='')
{
alert('please enter password');
return false;
}
}
</script>
{% endblock %}
templates/menu.html
{% extends 'dynamic_menu.html' %}
{% block body %}
{{request.user.username }}
{% if request.user.username != '' %}
<form method="post" action="{% url 'msave' %}">
{% csrf_token %}
<input type="text" placeholder="menu name :" name="menu_name"/><br/>
<input type="text" placeholder="menu link :" name="mn_link"/><br/>
<button type="submit" name="add_main_menu">Add main menu</button>
</form>
<table border="1">
<tr>
<th>slno</th>
<th>sitename</th>
<th>sitelink</th>
</tr>
{% for m in main_menu %}
<tr>
<td>{{ m.m_menu_id }}</td>
<td>{{ m.m_menu_name }}</td>
<td>{{ m.m_menu_link }}</td>
</tr>
{% endfor %}
</table>
{% endif %}
{% endblock %}
templates/submenu.html
{% extends 'dynamic_menu.html' %}
{% block body %}
<form method="post" action="{% url 'submenusave' %}">
{% csrf_token %}
<select name="parent">
<option selected="selected">select parent menu</option>
{% for m in m_menu %}
<option value="{{ m.m_menu_id }}">{{ m.m_menu_name }}</option>
{% endfor %}
</select>
<br/>
<input type="text" placeholder="menu name :" name="sub_menu_name"/><br/>
<input type="text" placeholder="menu link :" name="sub_menu_link"/><br/>
<button type="submit" name="add_sub_menu">Add sub menu</button>
</form>
<table border="1">
<tr>
<th>slno</th>
<th>parent menu id</th>
<th>sitename</th>
<th>sitelink</th>
</tr>
{% for s in s_submenu %}
<tr>
<td>{{s.s_menu_id }}</td>
<td>{{ s.m_menu_id }}</td>
<td>{{ s.s_menu_name }}</td>
<td>{{ s.s_menu_link }}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
templates/user_role_menu.html
{% extends 'dynamic_menu.html' %}
{% block body %}
<form method="post" action="{% url 'user_role_menu_save' %}">
{% csrf_token %}
<!--Blue select-->
<select name="user_name" id="user_name" class="mdb-select md-form colorful-select dropdown-primary">
<option selected="selected">Select User</option>
{% for user in user %}
<option value="{{ user.id }}">{{ user.username }}</option>
{% endfor %}
</select>
<label class="mdb-main-label">Select User</label>
<!--/Blue select-->
<!--Blue select-->
<select name="Role_name" id="Role_name" class="mdb-select md-form colorful-select dropdown-primary">
<option selected="selected">Select Role</option>
{% for usr_role in r_usrrole %}
<option value="{{ usr_role.id }}">{{ usr_role.Role_name }}</option>
{% endfor %}
</select>
<label class="mdb-main-label">Select Role</label>
<!--/Blue select-->
<div id="demo"></div>
<button type="submit" name="add_sub_menu">Add sub menu</button>
</form>
{% endblock %}
{% block script %}
<script>
// Material Select Initialization
$(document).ready(function() {
$('.mdb-select').materialSelect();
});
</script>
<script>
$(function() {
$("#user_name").change(function() {
var username=$('#user_name :selected').val()
// var role=$('option:selected', this).val();
$.ajax({
type: 'GET',
url: 'user_role_menu_edit',
data: {username:username},
dataType: "html",
contentType: 'multipart/form-data',
success: function (html) {
document.getElementById("demo").innerHTML = html
}
})
});
});
</script>
{% endblock %}
templates/user_role_menu1.html
{% for menu in r_menu %}
<div class="card">
<div class="card-body">
<div class="form-check">
<div class=" card-header white-text mb-3" style="background-color:#243a51">
<input type="checkbox" class="form-check-input" id="menu{{ menu.m_menu_id }}" name="menu[]"
value="{{ menu.m_menu_id }}" checked>
<label class="form-check-label" for="menu{{ menu.m_menu_id }}"> {{ menu.m_menu_name }}</label><br>
</div>
</div>
{% for sub in submenu %}
{% if sub.m_menu_id == menu.m_menu_id %}
<div class="form-check">
<input type="checkbox" class="form-check-input" id="submenu{{ sub.s_menu_id }}"
name="submenu_{{ menu.m_menu_id }}[]"
value="{{ sub.s_menu_id }}" checked>
<label class="form-check-label"
for="submenu{{ sub.s_menu_id }}"> {{ sub.s_menu_name }}</label><br>
</div>
{% endif %}
{% endfor %}
{% for sub in r_submenu %}
{% if sub.m_menu_id == menu.m_menu_id %}
<div class="form-check">
<input type="checkbox" class="form-check-input" id="submenu{{ sub.s_menu_id }}"
name="submenu_{{ menu.m_menu_id }}[]"
value="{{ sub.s_menu_id }}" >
<label class="form-check-label"
for="submenu{{ sub.s_menu_id }}"> {{ sub.s_menu_name }}</label><br>
</div>
{% endif %}
{% endfor %}
</div>
</div>
<br>
{% endfor %}
templates/user_role.html
{% extends 'dynamic_menu.html' %}
{% block body %}
<form method="post" action="{% url 'userroles_save' %}">
{% csrf_token %}
<input type="text" placeholder="role name :" name="Role_name"/><br/>
<button type="submit" name="role_create">Create role</button>
</form>
<table border="1">
<tr>
<th>slno</th>
<th>Role name</th>
<th>Role status</th>
</tr>
{% for role in usr_role %}
<tr>
<td></td>
<td>{{ role.Role_name }}</td>
<td>{{ role.role_status }}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
How to access model in all django templates
Sept. 8, 2021, 2:04 p.m.
442How to access model in all Django templates
When working with multiple and separate views, you may load different data objects into different views, but sometimes the use case requires you to have the same data available across the entire application — by that, I mean across all templates of the application. What would you do in that case? A beginner might repeat the process of loading data into a template context for each view, which is not so clever, right?
That’s exactly where custom context processors can be very useful.
We’ll see how we can put them in practice in just a moment, but let’s define a use case that would let you easily grasp what we’re about to implement.
Use Case:
You’re working on a course management system or LMS and you need to implement a search bar for available course subjects, and that search bar should be available across the entire application. For the sake of this quick tutorial, we’ll simply make the data available inside an HTML <option> or <ul> tag to list all the available subjects.
If you’re an intermediate Django developer, you’re probably aware of the Django template language, but don’t worry if you aren’t. Just remember that Django gives you the ability to create a base template and then add others by simply extending the base one. This is where you usually load all the static files. I included the link so you can look it up.
Implementation
To create a custom context processor, add a new file inside your app folder. We’ll call it custom_context_processor.py:
importing our models in custom_context_processor.py file
from .models import Subjectdef subject_renderer(request):
return {
‘all_subjects’: Subject.objects.all(),
}
A context processor is an interface:
- subject_renderer(request): A Python function that takes one argument which is a request object.
- all_subject: A list of available subjects returned as a dictionary.
That’s it for our context processor implementation and this is enough for our use case.
Now to make it accessible inside our templates, we need to add it inside our templates’ context, so open settings.py and add it like so:
settings.py
# …
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(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',
'your_app.custom_context_processor.subject_renderer'# add this
],
},
},
]
# …
We’ve made the function available across all our templates. It’s now time to render inside the _base.html and display the list of subjects:
templates/base.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{% block title %}{% endblock %}</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<! - CSS →
<link rel="stylesheet" href="">
<! - JS →
<script type="text/javascript"></script>
</head>
<body>
<u>
{% for s in all_subjects %}
<li><a href="{{ s.get_absolute_url }}">{{ s.title }}</a></li>
{% endfor %}
</u>
{% block content %}{% endblock %}
</body>
</html>
You can now navigate across all your application templates, and all your subjects will still be visible or accessible.
Send json as post to django using ajax
July 6, 2021, 7:41 p.m.
292Send JSON as POST to Django using Ajax
var csrftoken = Cookies.get('csrftoken');
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.setRequestHeader("content-type", "application/json");
}
}
});
for more click on this link:
how to send csrf token with ajax
How to send csrf token with ajax in django
July 6, 2021, 7:25 p.m.
293How to send csrf token with Ajax in django
<html>
<body>
<form enctype="multipart/form-data" id="id_ajax_upload_form" class="form-check" %}"
method="POST">
<input type="text" name="username" id="username">
<input type="text" password="password">
<input type="file" name="file">
<button style="font-size: 12px" type="submit" id="submit"
class="btn loc waves-effect mt-2"
>
Submit
</button>
</div>
</form>
<div id='demo'></div>
<script>
$(document).on('submit', '#id_ajax_upload_form', function (e) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
// serialize the data for sending the form data.
var serializedData_form = $(this).serialize();
var serializedData = new FormData($('#id_ajax_upload_form').get(0));
// make POST ajax call
//alert(serializedData);
$.ajax({
type: 'POST',
url: '{% url "register" %}',
data: serializedData, serializedData_form,
dataType: "html",
contentType: 'multipart/form-data',
processData: false,
contentType: false,
success: function (html) {
document.getElementById("demo").innerHTML = html
},
error: function (response) {
// alert the error if any error occured
$(demo).html('<div class="container">Error: something went wrong </span>')
}
})
});
}
</script>
</body>
How to view session data in django admin
July 6, 2021, 7:07 p.m.
108how to view session data in django admin
admin.py
from django.contrib import admin
from django.contrib.sessions.models import Session
from django.contrib.admin import ModelAdmin
# Register your models here.
class SessionAdmin(ModelAdmin):
def _session_data(self, obj):
return obj.get_decoded()
list_display = ['session_key', '_session_data', 'expire_date']
admin.site.register(Session, SessionAdmin)
Logout automatically on browser close in django
July 6, 2021, 7:04 p.m.
93Logout automatically on browser close in django
settings.py
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
Login and logout by django sessions and django user authentication
July 6, 2021, 6:30 p.m.
99Login and logout by django sessions and django user authentication
models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
mobile_phone = models.CharField(max_length=12, blank=True)
created_on = models.DateTimeField(auto_now_add=True)
Note:
createing custmized login decorator same as @login_required
def custom_decorator_logincheck(function):
print('custom_decorator_logincheck', function)
def _function(request, *args, **kwargs):
if request.session.get('user_email') is None:
# if empty means, empty string
# if request.session.get('user_email') is not None\
# and not request.session.get('user_email'):
return redirect('login')
return function(request, *args, **kwargs)
return _function
views.py
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout, get_user_model
from django.conf import settings
from kwikl3arn_app.models import *
def custom_decorator_logincheck(function):
print('custom_decorator_logincheck', function)
def _function(request, *args, **kwargs):
if request.session.get('user_email') is None:
# if empty means, empty string
# if request.session.get('user_email') is not None\
# and not request.session.get('user_email'):
return redirect('login')
return function(request, *args, **kwargs)
return _function
# login validation view
def login_page(request):
if request.user.is_authenticated:
return redirect(settings.LOGIN_REDIRECT_URL)
elif request.method == "POST":
email = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=email, password=password)
if user is None:
User = get_user_model()
user_queryset = User.objects.all().filter(email__iexact=email)
if user_queryset:
username = user_queryset[0].username
user = authenticate(username=username, password=password)
# if user created password with out hashing, it will check over here
if user is None:
User = get_user_model()
user = User.objects.filter(email=email, password=password).exists()
# if user is not exist it will return none
if user == False:
user = None
if user is not None:
try:
try:
login(request, user)
except Exception as e:
pass
request.session.set_expiry(14400) # session expire in 4 hrs
User = get_user_model()
user_queryset = User.objects.all().filter(email__iexact=email)
request.session['user_email'] = user_queryset[0].email
request.session['user_id'] = user_queryset[0].id
request.session['user_name'] = user_queryset[0].username
# request.session['_session_expiry'] = 14400
print('user loged in:', request.user.is_authenticated)
except AttributeError:
# if user created password with out hashing, it will check over here
# session creation
request.session['user_email'] = user[0].email
request.session['user_id'] = user[0].id
request.session['user_name'] = user[0].username
# once user is login it will print all sessions
for key, value in request.session.items():
print('{} => {}'.format(key, value))
# if user clicked something which is required login,
# after login it will redirect to that page,what ever user clicked
if 'next' in request.GET:
return redirect(request.GET['next'])
else:
return redirect('home')
else:
return render(request, 'login.html', context={'msg': 'Invalid User Name / Password'})
else:
return render(request, 'login.html', context={})
def logout_view(request):
try:
logout(request)
except:
try:
del request.session['user_email']
except:
return redirect('login')
return redirect('login')
@custom_decorator_logincheck
def home(request):
return render(request, 'home.html')
def registration(request):
if request.method == "POST":
user = User()
profile = Profile()
email = request.POST.get('email')
user.email = email
user.username = email
user.set_password('kwikl3arn123') # hashing password
user.save()
u = User.objects.get(email=email)
profile.user = User.objects.get(id=u.id)
profile.mobile_phone = request.POST.get('mobile_phone')
profile.user_name= request.POST.get('username')
profile.save()
return redirect('login')
urls.py
from django.contrib import admin
from django.urls import path
from kwikl3arn_app import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.login_page, name='login'),
path('logout', views.logout_view, name='logout'),
path('home', views.home, name="home"),
path('register', views.registration, name="register"),
]
settings.py
LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'home'
templates/register.html
<html>
<body>
<form method="post">
{% csrf_token %}
<input type="text" name="username" placeholder="user name">
<input type="text" name="email" placeholder="email">
<input type="text" name="mobile" placeholder="mobilenum">
<input type="submit">
</form>
</body>
</html>
templates/login.html
<html>
<body>
{% if msg %}
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<strong>Oo!</strong> {{ msg }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endif %}
<form method="post">
{% csrf_token %}
<input type="text" name="username" placeholder="useremail">
<input type="text" name="email" placeholder="email">
<input type="submit">
</form>
</body>
</html>
templates/home.html
<div class="container-fluid">
<nav class="navbar navbar-dark navcolor navbar-expand-lg ">
<a class="navbar-brand" href="{% url 'home' %}">LOGO/Title</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"><i class="fas fa-bars"></i></span>
</button>
{% if request.session.user_email %}
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
{% if request.resolver_match.url_name == 'home' %}
<li class="nav-item active">
{% else %}
<li class="nav-item">{% endif %}
<a class="nav-link" href="{% url 'home' %}">Home<span class="sr-only">(current)</span></a>
</li>
{% if request.session.user_email %}
{% else %}
{% if request.resolver_match.url_name == 'register' %}
<li class="nav-item active">
<a class="nav-link" href="{% url 'register' %}">Register</a>
</li>
{% else %}
<li class="nav-item">
<a class="nav-link" href="{% url 'register' %}">Register</a>
</li>
{% endif %}
{% endif %}
</ul>
<form class="form-inline my-2 my-lg-0">
{# <button class="btn btn-sm my-2 my-sm-0" type="submit"><i class="fa fa-power-off" aria-hidden="true" style="color: blanchedalmond;"></i></button>#}
{% if request.session.user_email %}
<ul class="nav navbar-nav nav-flex-icons">
<li class="nav-item dropdown">
<a class="nav-link text-capitalize" href="#" id="navbarDropdownMenuLink"
aria-haspopup="true" aria-expanded="false">
welcome {{ request.session.user_email }}
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'logout' %}"><i class="fas fa-power-off "
data-toggle="tooltip"
data-placement="bottom" title="Logout"></i></a>
</li>
</ul>
{% else %}
<a class="nav-link" href="{% url 'login' %}">Login</a>
{% endif %}
</form>
</div>
{% endif %}
</nav>
</div>
How to see session data in the django admin interface
July 1, 2021, 12:13 a.m.
128how to see session data in the admin interface
admin.py
from django.contrib.admin import ModelAdmin
# Register your models here.
class SessionAdmin(ModelAdmin):
def _session_data(self, obj):
return obj.get_decoded()
list_display = ['session_key', '_session_data', 'expire_date']
admin.site.register(Session, SessionAdmin)
Upload a file to s3 using boto3 in django
Dec. 22, 2020, 11:13 p.m.
430Upload a file to S3 using boto3 in django
Install:
pip3 install boto3
Set region and credentials
First we need to select the region where the bucket is placed and your account credentials.
- You can find the region in the url, when you preview the desired bucket https://s3.console.aws.amazon.com/s3/buckets/vperezb/?region=us-east-1 (In this case: region=us-east-1)
- Copy access and secret from https://console.aws.amazon.com/iam/home?#/security_credential (Security Credentials -> Access keys (access key ID and secret access key) -> Create New Access Key -> Show Access Key)
Using Account credentials isn’t a good practise as they give full access to AWS resources http://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html?icmpid=docs_iam_console
REGION = 'us-east-1'
ACCESS_KEY_ID = 'paste_here_your_key_id'
SECRET_ACCESS_KEY = 'paste_here_your_secret_access_key'
Select file to upload (computer)
PATH_IN_COMPUTER = 'path/in/computer/namefile.txt'
Select file destination (AWS S3)
BUCKET_NAME = 'vperezb'
KEY = 'path/in/s3/namefile.txt' # file path in S3
Upload the file to S3
s3_resource = boto3.resource(
's3',
region_name = REGION,
aws_access_key_id = ACCESS_KEY_ID,
aws_secret_access_key = SECRET_ACCESS_KEY
)
s3_resource.Bucket(BUCKET_NAME).put_object(
Key = KEY,
Body = open(PATH_IN_COMPUTER, 'rb')
)
All togeather
import boto3 REGION = 'us-east-1'
ACCESS_KEY_ID = 'paste_here_your_key_id'
SECRET_ACCESS_KEY = 'paste_here_your_secret_access_key'
PATH_IN_COMPUTER = 'path/in/computer/namefile.txt'
BUCKET_NAME = 'vperezb'
KEY = 'path/in/s3/namefile.txt' # file path in S3
s3_resource = boto3.resource(
's3',
region_name = REGION,
aws_access_key_id = ACCESS_KEY_ID,
aws_secret_access_key = SECRET_ACCESS_KEY
)
s3_resource.Bucket(BUCKET_NAME).put_object(
Key = KEY,
Body = open(PATH_IN_COMPUTER, 'rb')
)
How to upload file in multiple buckets in django
Dec. 4, 2020, 10:50 p.m.
642How to upload file in multiple buckets in django
install
boto3==1.11.12
Django==3.0.3
django-storages==1.9.1
Add storages
to the INSTALLED_APPS
in settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'upload',
'storages',
]
settings.py
# aws settings
AWS_ACCESS_KEY_ID = 'abcd34jj'
AWS_SECRET_ACCESS_KEY = 'your access key id'
AWS_STORAGE_BUCKET_NAME = 'bucket name here'
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
'CacheControl': 'max-age=86400',
}
AWS_LOCATION = 'static'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
PUBLIC_MEDIA_LOCATION = 'media'
MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/'
DEFAULT_FILE_STORAGE = 'your project name.storage_backends.PublicMediaStorage'
print(MEDIA_URL)
PRIVATE_FILE_STORAGE = 'your project name.storage_backends.AImediaStorage'
# <-- here is where we reference it for media
# DEFAULT_FILE_STORAGE = 'your project name.storage_backends.MediaStorage'
AWS_DEFAULT_ACL = None
add storage_backends.py in your project where settings.py is present
from storages.backends.s3boto3 import S3Boto3Storage
class MediaStorage(S3Boto3Storage):
location = 'media'
file_overwrite = False
class PublicMediaStorage(S3Boto3Storage):
location = 'media'
default_acl = 'public-read'
file_overwrite = False
# file upload to another bucket
class AImediaStorage(S3Boto3Storage):
bucket_name = 'kwikbucket' # bucketname
location = 'media'
default_acl = 'public-read'
models.py
import os
from datetime import datetime
from django.conf import settings
from django.contrib.auth.models import User
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.urls import reverse
from your project name.storage_backends import AImediaStorage
class ai_console_file(models.Model):
uploaded_by = models.ForeignKey(User, blank=True, null=True, related_name='ai_console_files',
on_delete=models.SET_NULL)
original_file_name = models.CharField(blank=True, null=True, max_length=1000)
rename_file = models.FileField(storage=AImediaStorage())# add this other wise it will store in default bucket
uploaded_on = models.DateTimeField(auto_now_add=True)
# rename file and upload to s3 bucket
def save(self, *args, **kwargs):
timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S.%f')
print("----------->", self.rename_file.name)
filename = self.rename_file.name[:10]
filename = filename.replace(' ', '_')
file_type = os.path.splitext(self.rename_file.name)[1]
print('filename=', self.rename_file.name)
print('file_type=', file_type)
print('renamefiles==', str(filename) + str(file_type))
rename = str(filename) + str(file_type)
print('self.document.name=', self.rename_file.name)
self.rename_file.name = str(timestamp) + '__' + str(rename)
print('file renamed=', self.rename_file.name)
super(ai_console_file, self).save(*args, **kwargs)
views.py
def pdf_doc_ai_files(request):
files = request.FILES.getlist('file')
print('files=', files)
if request.method == 'POST':
if files:
for myfile in files:
ai_console_file.objects.create(original_file_name=myfile, rename_file=myfile)
messages.success(request, "File uploaded successfully.")
return redirect('ai_upload_view')
else:
print('something went wrong')
return render(request, 'upload.html')
def ai_file_view(request):
return render(request, 'upload.html')
urls.py
from django.contrib import admin
from django.conf import settings
from django.urls import include, path, re_path
from myapp import views
from django.conf.urls import handler404, handler500, url, include
from django.contrib.auth import views as auth_views
urlpatterns = [
path('admin/', admin.site.urls),
path('ai_upload_view', views.ai_file_view, name="ai_upload_view"),
path('ai_upload', views.pdf_doc_ai_files, name="ai_upload"),
]
templates/upload.html
{% extends 'base.html' %}
{% load static %}
{% block body %}
<link rel="stylesheet" href="{% static 'css/flipcard.css' %}">
<div class="text-center">
<h3 class=" font-weight-bold">Upload File to another bucket</h3>
</div>
{% if messages %}
<div class="alert alert-success alert-dismissible fade show" role="alert">
{% for message in messages %}
<i class="fas fa-file-export"></i>
{% if message.tags %}
{% endif %}
{{ message }}
{% endfor %}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endif %}
<form method="post" action="{% url 'ai_upload' %}" enctype="multipart/form-data">
{% csrf_token %}
<div class="input-group">
<div class="input-group-prepend ">
<span class="input-group-text" id="inputGroupFileAddon01">Upload</span>
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" name="file" multiple accept=".doc,.docx,.ppt,.pptx,.pdf"
aria-describedby="inputGroupFileAddon01" onchange="return filevalid(this);">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
<button type="submit" id="submit" class="btn btn-outline-default waves-effect">upload</button>
<div class="row">
<div id="divFiles" class="files">
</div>
</div>
</form>
{% if msg %}
<div class="container">
<div class="row">
<div class="col-sm-4 my-3">
<div class="card card-flip h-100">
<div class="card-front text-white bg-info">
<div class="card-body">
<i class="fa fa-search fa-5x float-right"></i>
<h3 class="card-title">View Message</h3>
<p class="card-text text-white">Click here to see Message</p>
</div>
</div>
<div class="card-back bg-white">
<div class="card-body ">
<p class="card-text text-primary">
{{ x }}
</p>
</div>
</div>
</div>
</div>
</div>
</div>
{% endif %}
{% endblock %}
{% block script %}
<script>
function filevalid(fdata) {
// File extension validation, Add more extension you want to allow
var validExt = ".doc,.docx,.ppt,.pptx,.pdf";
var filePath = fdata.value;
var getFileExt = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
var pos = validExt.indexOf(getFileExt);
if (pos < 0) {
alert(fdata.files[0].name+" is not allowed, please upload (.doc,.docx,.ppt,.pptx,.pdf) files only.");
$('#submit').prop('disabled', true);
return false;
} else {
$('#submit').prop('disabled', false);
var file_name = fdata.files[0].name;//uploaded file name with extension
var filetype = filePath.replace(/^.*\./, '');//only extension type
//fileSizeValidate(fdata, file_name);
}
// file size validation
// size in kb
function fileSizeValidate(fdata, file_name) {
var maxSize = 200;
if (fdata.files && fdata.files[0]) {
var fsize = fdata.files[0].size / 1024;
if (fsize > maxSize) {
alert('Maximum file size upto 200KB, This file size is: ' + fsize + "KB");
return false;
} else {
return true;
}
}
}
}
</script>
{% endblock %}
for more
Storing django static and media files on amazon s3
Dec. 4, 2020, 10:37 p.m.
139Storing Django Static and Media Files on Amazon S3
install this
boto3==1.11.12
Django==3.0.3
django-storages==1.9.1
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'upload',
'storages',
]
Static Files
Moving along, we need to update the handling of static files in settings.py:
STATIC_URL = '/staticfiles/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
MEDIA_URL = '/mediafiles/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
Replace those settings with the following:
USE_S3 = os.getenv('USE_S3') == 'TRUE'
if USE_S3:
# aws settings
AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME')
AWS_DEFAULT_ACL = 'public-read'
AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'}
# s3 static settings
AWS_LOCATION = 'static'
STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
else:
STATIC_URL = '/staticfiles/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
MEDIA_URL = '/mediafiles/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
Public Media Files
To prevent users from overwriting existing static files, media file uploads should be placed in a different subfolder in the bucket. We'll handle this by creating custom storage classes for each type of storage.
Add a new file called storage_backends.py to the "app/hello_django" folder:
from storages.backends.s3boto3 import S3Boto3Storage
from django.conf import settings
class StaticStorage(S3Boto3Storage):
location = 'static'
default_acl = 'public-read'
class PublicMediaStorage(S3Boto3Storage):
location = 'media'
default_acl = 'public-read'
file_overwrite = False
Make the following changes to settings.py:
USE_S3 = os.getenv('USE_S3') == 'TRUE'
if USE_S3:
# aws settings
AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME')
AWS_DEFAULT_ACL = None
AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'}
# s3 static settings
STATIC_LOCATION = 'static'
STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{STATIC_LOCATION}/'
STATICFILES_STORAGE = 'hello_django.storage_backends.StaticStorage'
# s3 public media settings
PUBLIC_MEDIA_LOCATION = 'media'
MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/'
DEFAULT_FILE_STORAGE = 'hello_django.storage_backends.PublicMediaStorage'
else:
STATIC_URL = '/staticfiles/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/mediafiles/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
With the DEFAULT_FILE_STORAGE
setting now set, all FileFields will upload their content to the S3 bucket. Review the remaining settings before moving on.
Next, let's make a few changes to the upload
app.
app/upload/models.py:
from django.db import models
class Upload(models.Model):
uploaded_at = models.DateTimeField(auto_now_add=True)
file = models.FileField()
app/upload/views.py:
from django.shortcuts import render
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from .models import Upload
def image_upload(request):
if request.method == 'POST':
image_file = request.FILES['image_file']
image_type = request.POST['image_type']
if settings.USE_S3:
upload = Upload(file=image_file)
upload.save()
image_url = upload.file.url
else:
fs = FileSystemStorage()
filename = fs.save(image_file.name, image_file)
image_url = fs.url(filename)
return render(request, 'upload.html', {
'image_url': image_url
})
return render(request, 'upload.html')
Private Media Files
Add a new class to the storage_backends.py:
class PrivateMediaStorage(S3Boto3Storage):
location = 'private'
default_acl = 'private'
file_overwrite = False
custom_domain = False
Add the appropriate settings in settings.py
USE_S3 = os.getenv('USE_S3') == 'TRUE'
if USE_S3:
# aws settings
AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME')
AWS_DEFAULT_ACL = None
AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'}
# s3 static settings
STATIC_LOCATION = 'static'
STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{STATIC_LOCATION}/'
STATICFILES_STORAGE = 'hello_django.storage_backends.StaticStorage'
# s3 public media settings
PUBLIC_MEDIA_LOCATION = 'media'
MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/'
DEFAULT_FILE_STORAGE = 'hello_django.storage_backends.PublicMediaStorage'
# s3 private media settings
PRIVATE_MEDIA_LOCATION = 'private'
PRIVATE_FILE_STORAGE = 'hello_django.storage_backends.PrivateMediaStorage'
else:
STATIC_URL = '/staticfiles/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/mediafiles/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
Create a new model in app/upload/models.py:
from django.db import models
from hello_django.storage_backends import PublicMediaStorage, PrivateMediaStorage
class Upload(models.Model):
uploaded_at = models.DateTimeField(auto_now_add=True)
file = models.FileField(storage=PublicMediaStorage())
class UploadPrivate(models.Model):
uploaded_at = models.DateTimeField(auto_now_add=True)
file = models.FileField(storage=PrivateMediaStorage())
Then, update the view.py:
from django.shortcuts import render
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from .models import Upload, UploadPrivate
def image_upload(request):
if request.method == 'POST':
image_file = request.FILES['image_file']
image_type = request.POST['image_type']
if settings.USE_S3:
if image_type == 'private':
upload = UploadPrivate(file=image_file)
else:
upload = Upload(file=image_file)
upload.save()
image_url = upload.file.url
else:
fs = FileSystemStorage()
filename = fs.save(image_file.name, image_file)
image_url = fs.url(filename)
return render(request, 'upload.html', {
'image_url': image_url
})
return render(request, 'upload.html')
Django model admin sheet
Sept. 10, 2020, 5:29 p.m.
475Django model fields sheet
Sept. 10, 2020, 5:28 p.m.
155Django form fields sheet
Sept. 10, 2020, 5:27 p.m.
191Django template tags sheet
Sept. 10, 2020, 10:14 a.m.
156django template tags
How to create cookiecutter django projects
Aug. 2, 2020, 8:17 p.m.
358How to create Cookiecutter Django projects
Documentation: https://cookiecutter-django.readthedocs.io/en/latest/
install this
pip install "cookiecutter>=1.7.0"
type this in your terminal/cmd
cookiecutter https://github.com/pydanny/cookiecutter-django
after you type above command it will ask you like this as shown below
Cloning into 'cookiecutter-django'...
remote: Counting objects: 550, done.
remote: Compressing objects: 100% (310/310), done.
remote: Total 550 (delta 283), reused 479 (delta 222)
Receiving objects: 100% (550/550), 127.66 KiB | 58 KiB/s, done.
Resolving deltas: 100% (283/283), done.
project_name [Project Name]:example project
project_slug [reddit_clone]:example_project
author_name [dilip]: dilip
email [[email protected]]: [email protected]
description [Behold My Awesome Project!]:Example project.
domain_name [example.com]: example_project.com
version [0.1.0]: 0.0.1
timezone [UTC]: America/Los_Angeles
use_whitenoise [n]: n
use_celery [n]: y
use_mailhog [n]: n
use_sentry [n]: y
use_pycharm [n]: y
windows [n]: n
use_docker [n]: n
use_heroku [n]: y
use_compressor [n]: y
Select postgresql_version:
1 - 11.3
2 - 10.8
3 - 9.6
4 - 9.5
5 - 9.4
Choose from 1, 2, 3, 4, 5 [1]: 1
Select js_task_runner:
1 - None
2 - Gulp
Choose from 1, 2 [1]: 1
Select cloud_provider:
1 - AWS
2 - GCP
3 - None
Choose from 1, 2, 3 [1]: 1
custom_bootstrap_compilation [n]: n
Select open_source_license:
1 - MIT
2 - BSD
3 - GPLv3
4 - Apache Software License 2.0
5 - Not open source
Choose from 1, 2, 3, 4, 5 [1]: 1
keep_local_envs_in_vcs [y]: y
debug[n]: n
Enter the project and take a look around:
cd example_project/
$ ls
Create a git repo and push it there:
git init $ git add .
$ git commit -m "first awesome commit"
$ git remote add origin [email protected]:yourgithubname/yourrepositoryname
$ git push -u origin master
for devloping locally read this Developing locall
Quickest way create Cookiecutter Django project SQLite database
Start a new project
Just follow the instructions described in the usage docs. It boils down to running the following command:
$ cookiecutter https://github.com/pydanny/cookiecutter-django
Enter sensible answers to the questions asked, and you’ll be good to go. If you’re not sure whether you need a certain part, you probably can skip it. The defaults are great!
If you want to add something later, that’s fine. It might be a bit more work than selecting it right away, but not impossible.
Setup the project
Alright, the project folder is created and it’s filled with useful files. What now?
Now you need to create a new virtual environment for the project so you have a nice, clean place to work. I like to use virtualenvwrapper, but that’s a tool you don’t really need. Just very convenient in the long run.
Once you have your virtualenv set up, install local dependencies of the project.
$ pip install -r requirements/local.txt
We’re almost there!
This is where you would start tinkering with Docker, or start installing PostgreSQL. But you don’t have to, remember?
Simply set an environment variable to use an SQLite database:
$ export DATABASE_URL="sqlite:///db.sqlite"
This will make Django write data to a db.sqlite
file in the project’s root folder.
You’re all set! Now you can run the initial management commands and run the dev server
$ python manage.py migrate
$ python manage.py createsuperuser
$ python manage.py runserver
How to add two factor authentication for django admin
July 27, 2020, 11:02 a.m.
378how to add two factor authentication for django admin
the Implementation of TOTP validation with google authenticator for Django admin users. Main Aim of the project is add additional security feature for the admin users with TOTP validation.
django-admin.py startproject twofactordjango
pip install django-two-factor-auth
pip install django-two-factor-auth[phonenumbers]
settings.py
INSTALLED_APPS = [
'django_otp',
'django_otp.plugins.otp_static',
'django_otp.plugins.otp_totp',
'two_factor',
# django apps register below
]
MIDDLEWARE = [
'-------------------------------------------------------',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django_otp.middleware.OTPMiddleware',
'--------------------------------------------------------'
]
TWO_FACTOR_FORCE_OTP_ADMIN = True
LOGIN_URL = 'two_factor:login'
LOGIN_REDIRECT_URL = '/admin' # Redirect admin dashboard
Migrate all your installed apps
python manage.py makemigrations
python manage.py migrate
urls.py
from django.urls import path, include, re_path
from two_factor.urls import urlpatterns as tf_urls
from django.views.generic.base import TemplateView
from django.conf import settings
from django.http import HttpResponseRedirect
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.views import redirect_to_login
from django.shortcuts import resolve_url
from django.urls import reverse
from django.utils.http import is_safe_url
from two_factor.admin import AdminSiteOTPRequired, AdminSiteOTPRequiredMixin
class AdminSiteOTPRequiredMixinRedirSetup(AdminSiteOTPRequired):
def login(self, request, extra_context=None):
redirect_to = request.POST.get(
REDIRECT_FIELD_NAME, request.GET.get(REDIRECT_FIELD_NAME)
)
# For users not yet verified the AdminSiteOTPRequired.has_permission
# will fail. So use the standard admin has_permission check:
# (is_active and is_staff) and then check for verification.
# Go to index if they pass, otherwise make them setup OTP device.
if request.method == "GET" and super(
AdminSiteOTPRequiredMixin, self
).has_permission(request):
# Already logged-in and verified by OTP
if request.user.is_verified():
# User has permission
index_path = reverse("admin:index", current_app=self.name)
else:
# User has permission but no OTP set:
index_path = reverse("two_factor:setup", current_app=self.name)
return HttpResponseRedirect(index_path)
if not redirect_to or not is_safe_url(
url=redirect_to, allowed_hosts=[request.get_host()]
):
redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)
return redirect_to_login(redirect_to)
from django.contrib import admin
admin.site.__class__ = AdminSiteOTPRequiredMixinRedirSetup
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(tf_urls, "two_factor")),
path('', TemplateView.as_view(template_name="home.html"), name='home'),
]
in templates create new folder two_factor(templates/two_factor/) add below files inside that folder
_base.html
{% load i18n static %}<!DOCTYPE html>
{% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %}
<html lang="{{ LANGUAGE_CODE|default:"en-us" }}" {% if LANGUAGE_BIDI %}dir="rtl"{% endif %}>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" type="text/css" href="{% block stylesheet %}{% static "admin/css/base.css" %}{% endblock %}">
{% block extrastyle %}{% endblock %}
{% if LANGUAGE_BIDI %}<link rel="stylesheet" type="text/css" href="{% block stylesheet_rtl %}{% static "admin/css/rtl.css" %}{% endblock %}">{% endif %}
{% block extrahead %}{% endblock %}
{% block responsive %}
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0">
<link rel="stylesheet" type="text/css" href="{% static "admin/css/responsive.css" %}">
{% if LANGUAGE_BIDI %}<link rel="stylesheet" type="text/css" href="{% static "admin/css/responsive_rtl.css" %}">{% endif %}
{% endblock %}
{% block blockbots %}<meta name="robots" content="NONE,NOARCHIVE">{% endblock %}
</head>
{% load i18n %}
<body class="{% if is_popup %}popup {% endif %}{% block bodyclass %}{% endblock %}"
data-admin-utc-offset="{% now "Z" %}">
<!-- Container -->
<div id="container">
{% if not is_popup %}
<!-- Header -->
<div id="header">
<div id="branding">
{% block branding %}{% endblock %}
</div>
{% block usertools %}
{% if has_permission %}
<div id="user-tools">
{% block welcome-msg %}
{% trans 'Welcome,' %}
<strong>{% firstof user.get_short_name user.get_username %}</strong>.
{% endblock %}
{% block userlinks %}
{% if site_url %}
<a href="{{ site_url }}">{% trans 'View site' %}</a> /
{% endif %}
{% if user.is_active and user.is_staff %}
{% url 'django-admindocs-docroot' as docsroot %}
{% if docsroot %}
<a href="{{ docsroot }}">{% trans 'Documentation' %}</a> /
{% endif %}
{% endif %}
{% if user.has_usable_password %}
<a href="{% url 'admin:password_change' %}">{% trans 'Change password' %}</a> /
{% endif %}
<a href="{% url 'admin:logout' %}">{% trans 'Log out' %}</a>
{% endblock %}
</div>
{% endif %}
{% endblock %}
{% block nav-global %}{% endblock %}
</div>
<!-- END Header -->
{% block breadcrumbs %}
<div class="breadcrumbs">
<a href="{% url 'admin:index' %}">{% trans 'Home' %}</a>
{% if title %} › {{ title }}{% endif %}
</div>
{% endblock %}
{% endif %}
{% block messages %}
{% if messages %}
<ul class="messagelist">{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message|capfirst }}</li>
{% endfor %}</ul>
{% endif %}
{% endblock messages %}
<!-- Content -->
<div id="content" class="{% block coltype %}colM{% endblock %}">
{% block pretitle %}{% endblock %}
{% block content_title %}{% if title %}<h1>{{ title }}</h1>{% endif %}{% endblock %}
{% block content %}
{% block object-tools %}{% endblock %}
{{ content }}
{% endblock %}
{% block sidebar %}{% endblock %}
<br class="clear">
</div>
<!-- END Content -->
{% block footer %}<div id="footer"></div>{% endblock %}
</div>
<!-- END Container -->
</body>
</html>
_base_focus.html
{% extends "admin/base_site.html" %}
{% load i18n static %}
{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/login.css" %}">
{{ form.media }}
{% endblock %}
{% block bodyclass %}{{ block.super }} login{% endblock %}
{% block usertools %}{% endblock %}
{% block nav-global %}{% endblock %}
{% block content_title %}{% endblock %}
{% block breadcrumbs %}{% endblock %}
{% block content %}
{% endblock %}
inside templates i have added another home.html(templates/home.html)
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="jumbotron text-center">
<h1>My First Bootstrap Page</h1>
<p>Resize this responsive page to see the effect!</p>
</div>
<div class="container">
<div class="row">
<div class="col-sm-4">
<h3>Column 1</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
</div>
<div class="col-sm-4">
<h3>Column 2</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
</div>
<div class="col-sm-4">
<h3>Column 3</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
</div>
</div>
</div>
</body>
</html>
now create superuser
python manage.py createsuperuser
Once you have created superuser, login with the admin dashboard, the django-two-factor-auth will force you to enable two factor authentication.
for more https://django-two-factor-auth.readthedocs.io/en/stable/requirements.html
Add two factor authentication in django
July 26, 2020, 8:12 p.m.
172Add Two Factor Authentication in django
Two factor authentication became very popular lately as many sites started offering this option. 2FA performs authentication using two things:
- Something you know — Usually a password.
- Something you have — Usually a mobile app that generates a random number every 30 seconds (such as Authenticator by Google).
On first signup the user is usually asked to scan a barcode with the authenticator app. After this initial setup the app will start generating the one-time codes.
I don’t usually recommend third party packages, but a couple of months ago we started using django-otp to implement 2FA in our admin site and it’s working great for us. It’s hosted on Bitbucket so you might have missed it.
The setup is pretty simple:
pip install django-otp
pip install qrcode
Add django-otp to the installed apps and the middleware:
# settings.py
INSTALLED_APPS = (
...
‘django_otp’,
‘django_otp.plugins.otp_totp’,
...
)
MIDDLEWARE = (
...
‘django.contrib.auth.middleware.AuthenticationMiddleware’,
‘django_otp.middleware.OTPMiddleware’,
...
)
# Name the issuer — this is the name users will see in the authenticator app, so make it distinguishable.
OTP_TOTP_ISSUER = ‘kwikl3arn.com’
Run migrations
python manage.py makemigrations
python manage.py migrate
Add 2FA authentication to the admin site:
urls.py
from django_otp.admin import OTPAdminSite
# admin.site.__class__ = OTPAdminSite
class OTPAdmin(OTPAdminSite):
pass
from django.contrib.auth.models import User
from django_otp.plugins.otp_totp.models import TOTPDevice
admin_site = OTPAdmin(name='OTPAdmin')
admin_site.register(User)
admin_site.register(TOTPDevice)
urlpatterns = [
path('admin', admin_site.urls),#this will ask OTP Token
path('myadmin', admin.site.urls),#this is normal admin
]
first login with myadmin.then click on TOTP devices,
now click on Add TOTP device,then select user,and give name and click on save.after saveing open that user. at the end u can see qr code,click on that qr code.so you can see the qrcode generated for that user.
scan that qr code with Authenticator by Google.
Automatically register all models in django admin
July 26, 2020, 7:36 p.m.
236Automatically Register All Models In Django Admin
How To Automatically Register All Models In Django Admin?
The inbuilt admin interface is one of the most powerful & popular features of Django. Once we create the models, we need to register them with the admin interface, so that it can read metadata and populate interface for it.
If the Django project has too many models or if it has a legacy database, then adding all those models to admin becomes a tedious task. To automate this process, we can programmatically fetch all the models in the project and register them with the admin interface.
Open admin.py file and add this code to it.
from django.apps import apps
models = apps.get_models()
for model in models:
admin.site.register(model)
This will fetch all the models in all apps and registers them with the admin interface.
This works well if we are automatically registering all the models. However, if we separately register some models with customizations and try to register all models in our apps again, there will be conflicts as Django doesn't allow registering the same model twice.
So, we need to make sure this piece of code runs at the end of admin.py file and it should ignore models which are already registered. We can add this code at the end of the admin.py file.
from django.apps import apps
from book.models import Book
class BookAdmin(admin.ModelAdmin):
list_display = ('name', 'author')
# model registered with custom admin
admin.site.register(Book, BookAdmin)
# all other models
models = apps.get_models()
for model in models:
try:
admin.site.register(model)
except admin.sites.AlreadyRegistered:
pass
Now manually registered models will get registered first followed by automatic registration of remaining models.
class Book(models.Model):
name = models.CharField(max_length=100)
author = models.ForeignKey(Author, null=True)
borrowed = models.CharField(max_length=100, default='')
def __str__(self):
return self.name
If we go to a model page in admin, automatically registered models .
This interface is not informative for the users who want to see the data. To improve that, we can create a
ListAdminMixin
, which will populate
list_display
with all the fields in the model.
We can create a new admin class which will subclass
ListAdminMixin
&
ModelAdmin
. We can use this admin class when we are registering the model so that all the fields in the model will show up in the admin.
from django.apps import apps
from django.contrib import admin
class ListAdminMixin(object):
def __init__(self, model, admin_site):
self.list_display = [field.name for field in model._meta.fields]
super(ListAdminMixin, self).__init__(model, admin_site)
models = apps.get_models()
for model in models:
admin_class = type('AdminClass', (ListAdminMixin, admin.ModelAdmin), {})
try:
admin.site.register(model, admin_class)
except admin.sites.AlreadyRegistered:
pass
Now, whenever we create a new model or add a new field to an existing model, it will get reflected in the admin automatically.
With this, we can avoid registering models with admin whenever models get added to our apps.
Login sessions for django
July 24, 2020, 1:08 a.m.
197login sessions for django
views.py
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
if request.method == 'POST':
username = request.POST.get('nickname','')
password = request.POST.get('password','')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
request.session.set_expiry(86400) #sets the exp. value of the session
login(request, user) #the user is now logged in
And for the other sites (where you need to be loggedin):
def my_func(request):
if request.user.is_authenticated():
print (user.id) #the user is loggedin
Or you use the login_require
-decorator:
from django.contrib.auth.decorators import login_required
@login_required
def my_func(request):
print(user.id) #the user is loggedin
How to display all session in django?
July 24, 2020, 1:03 a.m.
175How to display all session variables in django?
from below code we can print all session which are present in django.
for key, value in request.session.items():
print('{} => {}'.format(key, value))
On login redirect / return to same (previous) page in django?
July 21, 2020, 8:41 p.m.
202Redirect / return to same (previous) page in Django?
In django view suppose you are not logged in but click on some content that content trigger some url like /grant-update/2 then @login_required will redirect you to login page with this url
http://127.0.0.1:8000/login?next=/grant-update/1
so our aim is redirect to http://127.0.0.1:8000/grant-update/1 page after successful login
install this
pip install django-crispy-forms
settings.py
INSTALLED_APPS = [
...
'crispy_forms',
]
CRISPY_TEMPLATE_PACK = 'bootstrap4'
models.py
class grantapplication(models.Model):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
forms.py
from django import forms
from MyApp.models import grantapplication
class GrantApplicationForm(forms.ModelForm):
# ---removing all form label by using crispy_forms
def __init__(self, *args, **kwargs):
super(GrantApplicationForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_show_labels = False
class Meta:
model = grantapplication
fields = "__all__"
class LoginForm(forms.Form):
name = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control"}))
password=forms.CharField(widget=forms.PasswordInput(attrs={"class": "form-control"}))
views.py
from django.shortcuts import render, get_object_or_404, redirect
from MyApp.models import grantapplication
from MyApp.forms import LoginForm
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
def login_page(request):
if request.method == "POST":
lform = LoginForm(request.POST or None)
content = {'lform': lform}
print(lform.changed_data)
username = request.POST.get('name')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user and user.is_active:
login(request, user)
print('user loged in:', request.user.is_authenticated)
# if user clicked something which is required login,
# after login it will redirect to that page,what ever user clicked
if 'next' in request.GET:
return redirect(request.GET['next'])
else:
return redirect('grant-list')
else:
return render(request, 'myapp/login.html', content)
else:
lform = LoginForm()
content = {'lform': lform}
return render(request, 'myapp/login.html', content)
@login_required
def logout_view(request):
logout(request)
return redirect('login')
@login_required
def grant_app_list(request):
qs = grantapplication.objects.all()
template_name = 'grant_app_list.html'
context = {'grant_list': qs}
return render(request, template_name, context)
@login_required
def grant_app_update(request, id=None):
qs = get_object_or_404(grantapplication, id=id)
form = GrantApplicationForm(request.POST or None, instance=qs)
template_name = 'grant_update.html'
if form.is_valid():
form.save()
form = GrantApplicationForm
else:
pass
context = {'form': form, 'id': qs.id}
return render(request, template_name, context)
urls.py
from django.urls import path,
from MyApp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.grant_app_view, name='grantapplicationview'),
path('grant-list', views.grant_app_list, name='grant-list'),
path('grant-update/<int:id>', views.grant_app_update, name='grant-update'),
path('login', views.login_page, name='login'),
path('logout', views.logout_view, name='logout'),
]
grant_app_list.html
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">view</th>
</tr>
</thead>
<tbody>
{% for list in grant_list %}
<tr>
<th scope="row">{{ forloop.counter }}</th>
<td>{{ list.firstname|capfirst }}</td>
<td>{{ list.lastname|capfirst }}</td>
<td><a href="{% url 'grant-update' list.id %}" class="btn btn-secondary btn-sm " role="button" aria-pressed="true">update</a></td>
</tr>
{% endfor %}
</tbody>
</table>
grant_update.html
{% load crispy_forms_tags %}
<form action="{% url 'grant-update' id %}" method="post">
<div class="form-group">
<label for="firstname">*First Name</label>
{{ form.firstname|as_crispy_field }}
</div>
<div class="form-group">
<label for="lastname">*Last Name</label>
{{ form.lastname|as_crispy_field }}
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
login.html
<form method="post">
{% csrf_token %}
{{ lform }}
<br>
<div class="form-group clearfix">
<div>
<button type="submit" name="" id="" class="btn btn-primary btn-md btn-block">Login</button>
</div>
</form>
Amazon s3 bucket for static and media files for django project
July 21, 2020, 2:44 a.m.
216Amazon S3 bucket for static and media files for django project
You will need to install two Python libraries
pip install boto3
pip install django-storages
The boto3 library is a public API client to access the Amazon Web Services (AWS) resources, such as the Amazon S3. It’s an official distribution maintained by Amazon.
The django-storages is an open-source library to manage storage backends like Dropbox, OneDrive and Amazon S3. It’s very convenient, as it plugs in the built-in Django storage backend API. In other words, it will make you life easier, as it won’t drastically change how you interact with the static/media assets. We will only need to add a few configuration parameters and it will do all the hard work for us.
settings.py
INSTALLED_APPS = [
'storages',
]
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
AWS_ACCESS_KEY_ID = 'AKIAIT2Z5TDYPX3ARJBA'
AWS_SECRET_ACCESS_KEY = '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'
AWS_STORAGE_BUCKET_NAME = 'staticfiles-django'
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
AWS_LOCATION = 'static'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
#note here frankie is myproject name,replace frankie with u r projectname
DEFAULT_FILE_STORAGE = 'frankie.storage_backends.MediaStorage' # <-- here is where we reference it for media
AWS_DEFAULT_ACL = None
create storage_backends.py where settings.py file present the folder
storage_backends.py
from storages.backends.s3boto3 import S3Boto3Storage
class MediaStorage(S3Boto3Storage):
location = 'media'
file_overwrite = False
Even though we are using our local machine, we will need to run the collectstatic
command, since our code will refer to a remote location:
python manage.py collectstatic
How to create custom middleware in django
July 10, 2020, 8:45 p.m.
287How to create custom middleware in django
What is Middleware?
Middleware is a way to hook some functionality into request/response processing of Django Framework.
Each middleware is meant to perform some process either before request is processed or/and after request is processed.
Creating Custom Middleware
Here are the steps to create a custom middleware that is used to add copyright information at the end of all responses.
Create function called footer() in module footer_middleware.py. The function footer() is supposed to return a function (middleware() in this case) that is to be hooked in request pipeline.
The function returned by footer() must itself return an object of type Response.
It is also calling get_response() method to get access to response after view is processed.
Lets create a new project:
django-admin.py startproject custom_middleware
Lets create new app:
python manage.py startapp MyApp
now lets create custom middleware in our app
Myapp/footer_middleware.py
footer_middleware.py
from django.shortcuts import render, redirect
def footer(get_response):
# One-time configuration and initialization.
# this function is called for every view
def middleware(request):
# do process before view is called here
response = get_response(request)
# do process after view is called as response is generated
response.write(
"<p></p><hr/><div style='color:blue;text-align:center'>Copyright © kwikl3arn.com All rights reserved.</div>")
return response
return middleware
settings.py
MIDDLEWARE = [
'MyApp.footer_middleware.footer',#add this
]
views.py
from django.shortcuts import render
def demo_page(request):
return render(request, 'demo.html')
templates/demo.html
demo.html
<h1>this is demo page</h1>
<p>now you can see footer on this page if you run in browser</p>
urls.py
from django.contrib import admin
from django.urls import path
from MyApp import views
urlpatterns = [
path("admin/", admin.site.urls),
path('',views.demo_page, name='demo'),
]
How to send email with django
July 7, 2020, 11:42 p.m.
211How To Send Email With Django
settings.py
# login to your email try below urls
# Allow less secure apps: ON at [https://myaccount.google.com/lesssecureapps]
# click continue button at [https://accounts.google.com/displayunlockcaptcha]
# disable 2 factor authentication
# generate a app password separate if you don't want to use your email password at [https://myaccount.google.com/apppasswords]
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '[email protected]'# your email
EMAIL_HOST_PASSWORD = 'uwtftrnwitaxzdjp'# here your email password for generated app password
EMAIL_PORT = 587
views.py
from django.shortcuts import render
from django.core.mail import send_mail
from django.conf import settings
# Create your views here.
def index(request):
return render(request, 'mail.html', {})
def mailsub(request):
print('type:', request.method)
if request.method == 'POST':
message_name = request.POST['message_name']
message_email = request.POST['message_email']
message = request.POST['message']
print(message_name)
print(message_email)
print(message)
send_mail(
message_name, # subject
message, # message
settings.EMAIL_HOST_USER, # from email
# ["[email protected]", '[email protected]'], # to email
#or
message_email.strip('][').split(','), # to email
fail_silently=False)
return render(request, 'mail.html', {'message': 'thank you for sending email for us'})
else:
return render(request, 'mail.html', {})
urls.py
from django.contrib import admin
from django.urls import path
from MyApp import views
urlpatterns = [
path("admin/", admin.site.urls),
path("", views.index, name="mymail"),
path("mailsub", views.mailsub, name="mailsub"),
]
mail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
{% if message %}
{{message}}
{% else %}
<form method="POST" action="{% url 'mailsub' %}">
{% csrf_token %}
<input name="message_name" placeholder="subject" />
<input name="message_email" placeholder="user email" />
<input name="message" placeholder="your message" />
<input type="submit" value="submit" />
</form>
{% endif %}
</body>
</html>
How to use faker in django
June 28, 2020, 9:35 a.m.
303How to use FAKER in django
What is faker?
Faker is a Python package that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill-in your persistence to stress test it, or anonymize data taken from a production service, Faker is for you.
installing faker
pip install Faker
Basic Usage
Use faker.Faker()
to create and initialize a faker generator, which can generate data by accessing properties named after the type of data you want.
from faker import Faker
fake = Faker()
fake.name()
# 'Lucy Cechtelar'
fake.address()
# '426 Jordy Lodge
# Cartwrightshire, SC 88120-6700'
fake.text()
# 'Sint velit eveniet. Rerum atque repellat voluptatem quia rerum. Numquam excepturi
# beatae sint laudantium consequatur. Magni occaecati itaque sint et sit tempore. Nesciunt
# amet quidem. Iusto deleniti cum autem ad quia aperiam.
Each call to method fake.name()
yields a different (random) result. This is because faker forwards faker.Generator.method_name()
calls to faker.Generator.format(method_name)
.
for _ in range(4):
print(fake.name())
# 'Adaline Reichel'
# 'Dr. Santa Prosacco DVM'
# 'Noemy Vandervort V'
# 'Lexi O'Conner'
For more about faker visit this link: https://faker.readthedocs.io/en/master/index.html#
Lets create a project in django
django-admin startproject first_project
Lets create a django application
python manage.py startapp first_app
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'first_app'#add the app name
]
models.py
from django.db import models
# Create your models here.
class Topic(models.Model):
top_name=models.CharField(max_length=24,unique=True)
def __str__(self):
return self.top_name
class Webpage(models.Model):
topic=models.ForeignKey(Topic,on_delete=models.CASCADE)
name=models.CharField(max_length=264,unique=True)
url=models.URLField(unique=True)
def __str__(self):
return self.name
class AccessRecord(models.Model):
name=models.ForeignKey(Webpage,on_delete=models.CASCADE)
date=models.DateField()
def __str__(self):
return self.date
RUN:
python manage.py migrate
python manage.py makemigrations first_app
python manage.py migrate
admin.py
from django.contrib import admin
from first_app.models import Topic,Webpage,AccessRecord
# Register your models here.
admin.site.register(Topic)
admin.site.register(Webpage)
admin.site.register(AccessRecord)
now ceate a populat_first_app.py inside Your project.
first_project/
├── first_app
├── first_project
├── manage.py
├── populat_first_app.py
populat_first_app.py
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings')
import django
django.setup()
#Fake Pop Script
import random
from first_app.models import Topic,Webpage,AccessRecord
from faker import Faker
fakegen=Faker()
topics=['search','news','games','movies','social']
def add_topic():
t=Topic.objects.get_or_create(top_name=random.choice(topics))[0]
t.save()
return t
def populate(n=5):
for entry in range(n):
# get the topic name for entry
top=add_topic()
#creating fake data for entry
fake_url=fakegen.url()
fake_date=fakegen.date()
fake_name=fakegen.company()
#create webpage entry
webpage=Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0]
#create Access Record entry
acc_record=AccessRecord.objects.get_or_create(name=webpage,date=fake_date)[0]
if __name__=='__main__':
print('printing populateing')
populate(20)
print('populate complete')
RUN:
python populat_first_app.py
now check your data base it will create fake data in all our tables
create super user and check it
python manage.py createsuperuser
after creating super user run the server
python manage.py runserver
http://127.0.0.1:8000/admin
enter your user name and password ,which is created in super user and login
How to create custom template filter in django
June 25, 2020, 3:39 p.m.
177How to create custom template filter in django
Lets create a project in django
django-admin startproject first_project
Lets create a django application
python manage.py startapp first_app
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'first_app'#add the app name
]
now ceate a new folder temlates inside your app,in that folder create my_extras.py and __init__.py as show in below
first_project/
├── first_app
│ ├── __init__.py
│ ├── admin.py
│ ├── views.py
│ └──templatetags
│ ├── __init__.py
│ └── my_extras.py
├── first_project
├── manage.py
└── templates
├──index.html
my_extra.py
from django import template
register=template.Library()
def cute(value,arg):
"""
This cuts all values of 'arg' from the string
"""
return value.replace(arg,'')
register.filter('cut',cute)#'cut' is used for template and another cute is a function
my_extra.py by useing decorators
from django import template
register=template.Library()
# by using decorator we can create
@register.filter(name='cut')
def hi(value,arg):
"""
This cuts all values of 'arg' from the string
"""
return value.replace(arg,'')
views.py
from django.shortcuts import render
def index(request):
my_dict={'name':'hello world','site':'kwikl3arn django'}
return render(request,'index.html',context=my_dict)
urls.py
from django.urls import path
from first_app import views
urlpatterns=[
path('',views.index,name='index')
]
index.html
<html>
<body>
<h1>{{name}}</h1>
<h1>{{site}}</h1>
</body>
</html>
RUN:
python manage.py runserver
output:
hello world kwikl3arn django
lets apply filter that we create
<html>
<body>
<h1>{{name|cut:'hello'}}</h1>
<h1>{{site|cut:'kwikl3arn'}}</h1>
</body>
</html>
output
world django
Replace the image in an <img> with css
May 30, 2020, 12:22 p.m.
410Replace the Image in an <img> with CSS
<style>
.image-replacement {
display: block;
-moz-box-sizing: border-box;
box-sizing: border-box;
background: url(http://akamaicovers.oreilly.com/images/9780596517748/cat.gif) no-repeat;
width: 180px;
height: 236px;
padding-left: 180px;
}
</style>
<h2>Image replaced with Image</h2>
<img class="image-replacement" src="http://akamaicovers.oreilly.com/images/9781593272869/cat.gif" />
this code will prevent user downloading our files from the website.
How to use charts in django
April 8, 2020, 10:41 p.m.
436How to use charts in django
installation
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.min.js"></script>
or
You can download it from Chart.js
models.py
class Country(models.Model):
name = models.CharField(max_length=30)
class City(models.Model):
name = models.CharField(max_length=30)
country = models.ForeignKey(Country, on_delete=models.CASCADE)
population = models.PositiveIntegerField()
views.py
from django.shortcuts import render
from kwikl3arn.models import City
def pie_chart(request):
labels = []
data = []
queryset = City.objects.order_by('-population')[:5]
for city in queryset:
labels.append(city.name)
data.append(city.population)
return render(request, 'pie_chart.html', {
'labels': labels,
'data': data,
})
urls.py
from django.urls import path
from kwikl3arn import views
urlpatterns = [
path('pie-chart/', views.pie_chart, name='pie-chart'),
]
pie_chart.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div id="container" style="width: 75%;">
<canvas id="pie-chart"></canvas>
</div>
</body>
</html>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.min.js"></script>
<script>
var config = {
type: 'pie',
data: {
datasets: [{
data: {{ data|safe }},
backgroundColor: [
'#696969', '#808080', '#A9A9A9', '#C0C0C0', '#D3D3D3'
],
label: 'Population'
}],
labels: {{ labels|safe }}
},
options: {
responsive: true
}
};
window.onload = function() {
var ctx = document.getElementById('pie-chart').getContext('2d');
window.myPie = new Chart(ctx, config);
};
</script>
Note:
Please enter some some data after creating models,other wise you cant see the charts
for more please check this https://www.chartjs.org/docs/latest/charts/doughnut.html
Pip upgrade all packages at once in linux
April 8, 2020, 10:08 a.m.
230Pip upgrade all packages at once in linux
This is a Linux one-liner that takes all the contents of the requirements file and upgrades them one by one.
$ pip3 list -o --format columns| cut -d' ' -f1|xargs -n1 pip install -U
Let’s explain how that command works.
pip3 list -o
: shows the outdated packages--format columns
: specifies how to print the output
cut -d' '
: split the input by spaces-f1
: and take the first field of each line
xargs -n1
: use at most 1 arg by command linepip install -U
: upgrade the package
you may see output something like this
$ pip3 list -o --format columns
Package Version Latest Type
------------------------- --------- ---------- -----
beautifulsoup4 4.6.3 4.7.1 wheel
certifi 2018.8.24 2018.11.29 wheel
Django 2.1.1 2.1.5 wheel
django-allauth 0.37.1 0.38.0 sdist
django-autocomplete-light 3.3.1 3.3.2 sdist
django-sendgrid-v5 0.7.0 0.7.1 wheel
Faker 0.9.1 1.0.2 wheel
idna 2.7 2.8 wheel
oauthlib 2.1.0 3.0.1 wheel
pip 18.1 19.0.1 wheel
psycopg2-binary 2.7.5 2.7.7 wheel
pycountry 18.5.26 18.12.8 wheel
python-dateutil 2.7.3 2.7.5 wheel
pytz 2018.5 2018.9 wheel
requests 2.19.1 2.21.0 wheel
requests-oauthlib 1.0.0 1.2.0 wheel
setuptools 40.6.3 40.7.2 wheel
six 1.11.0 1.12.0 wheel
urllib3 1.23 1.24.1 wheel
whitenoise 4.1 4.1.2 wheel
$ pip3 list -o --format columns| cut -d' ' -f1
Package
-------------------------
beautifulsoup4
certifi
Django
django-allauth
django-autocomplete-light
django-sendgrid-v5
Faker
idna
oauthlib
pip
psycopg2-binary
pycountry
python-dateutil
pytz
requests
requests-oauthlib
setuptools
six
urllib3
whitenoise
$ pip3 list -o --format columns| cut -d' ' -f1|xargs -n1 pip install -U
.....
Collecting beautifulsoup4
Using cached https://files.pythonhosted.org/packages/1d/5d/3260694a59df0ec52f8b4883f5d23b130bc237602a1411fa670eae12351e/beautifulsoup4-4.7.1-py3-none-any.whl
Collecting soupsieve>=1.2 (from beautifulsoup4)
Using cached https://files.pythonhosted.org/packages/bf/b3/2473abf05c4950c6a829ed5dcbc40d8b56d4351d15d6939c8ffb7c6b1a14/soupsieve-1.7.3-py2.py3-none-any.whl
Installing collected packages: soupsieve, beautifulsoup4
Found existing installation: beautifulsoup4 4.6.3
Uninstalling beautifulsoup4-4.6.3:
Successfully uninstalled beautifulsoup4-4.6.3
Successfully installed beautifulsoup4-4.7.1 soupsieve-1.7.3
....
Generating slugs automatically in django
April 8, 2020, 9:27 a.m.
200Generating slugs automatically in Django
models.py
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(
default='1',
unique=True,
max_length=settings.BLOG_TITLE_MAX_LENGTH,)
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Article, self).save(*args, **kwargs)
when ever user click on save,slug will take title and replaces spaces by hyphens
As SlugField inherits from CharField, it comes with the attribute max_length which handles the maximum length of the string it contains at database level.
If we use a SlugField without specifying its max_length attribute, it gets the value of 50 by default, which can lead to problems when we generate the string from a bigger max_length field
Second approach: unique slugs
In this case title and slug don’t need to have the same max_length, but this brings two issues when generating the slug:
- Truncate the slug to respect max_length
- Control the slug uniqueness by adding a suffix if another slug with the same string exists1
- Avoid generating a new slug if it already has one when saving an existing instance
1. Truncate the slug
Before generating the slug, get the max_length value max_length = self._meta.get_field('slug').max_length and truncate at that position slug = slugify(self.title)[:max_length].
2. Ensure uniqueness
For each slug candidate we make sure it is unique by testing against the database until we have a non existing one.
models.py
from django.conf import settings
from django.db import models
from django.urls import reverse
from django.utils.text import slugify
import itertools
class ArticlePkAndSlug(models.Model):
title = models.CharField(
max_length=settings.BLOG_TITLE_MAX_LENGTH
)
slug = models.SlugField(
default='',
editable=False,
max_length=settings.BLOG_TITLE_MAX_LENGTH,
)
def get_absolute_url(self):
kwargs = {
'pk': self.id,
'slug': self.slug
}
return reverse('article-pk-slug-detail', kwargs=kwargs)
def save(self, *args, **kwargs):
value = self.title
self.slug = slugify(value, allow_unicode=True)
super().save(*args, **kwargs)
class ArticleUniqueSlug(Article):
def _generate_slug(self):
max_length = self._meta.get_field('slug').max_length
value = self.title
slug_candidate = slug_original = slugify(value, allow_unicode=True)
for i in itertools.count(1):
if not ArticleUniqueSlug.objects.filter(slug=slug_candidate).exists():
break
slug_candidate = '{}-{}'.format(slug_original, i)
self.slug = slug_candidate
def save(self, *args, **kwargs):
if not self.pk:
self._generate_slug()
super().save(*args, **kwargs)
views.py
from django.views.generic.detail import DetailView
from .models import Article
class ArticleDetailView(DetailView):
model = Article
class Article(DetailView):
model = ArticlePkAndSlug
query_pk_and_slug = False
urls.py
from django.urls import path
from kwikl3arn.views import ArticleDetailView
urlpatterns = [
path('kwikl3arn/<int:pk>/', ArticleDetailView.as_view(), name='article-detail1'),
path('kwikl3arn/<int:pk>-<str:slug>/', ArticleDetailView.as_view() , name='article-detail2')
]
Ckeditor in django
April 8, 2020, 7:32 a.m.
464CKeditor in Django
Install
pip install django-ckeditor
pip install pillow
settings.py
INSTALLED_APPS = [ ... ,
'ckeditor',
'ckeditor_uploader',
]
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')
STATIC_URL = '/static/'
from filebrowser.sites import site
site.directory = "uploads/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
SITE_ID = 1
# LOGIN_URL = 'login'
CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js'
CKEDITOR_UPLOAD_PATH = 'uploads/'
CKEDITOR_IMAGE_BACKEND = "pillow"
CKEDITOR_CONFIGS = {
'default': {
'skin': 'kama',
# 'skin': 'office2013',
'codeSnippet_theme': 'atelier-seaside.dark',
'toolbar_Basic': [
['Source', '-', 'Bold', 'Italic']
],
'toolbar_YourCustomToolbarConfig': [
{'name': 'document', 'items': ['Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates']},
{'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']},
{'name': 'editing', 'items': ['Find', 'Replace', '-', 'SelectAll']},
{'name': 'forms',
'items': ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',
'HiddenField']},
'/',
{'name': 'basicstyles',
'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']},
{'name': 'paragraph',
'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-',
'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl',
'Language']},
{'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']},
{'name': 'insert',
'items': ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe']},
'/',
{'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']},
{'name': 'colors', 'items': ['TextColor', 'BGColor']},
{'name': 'tools', 'items': ['ShowBlocks']},
{'name': 'about', 'items': ['About']},
'/', # put this to force next toolbar on new line
{'name': 'yourcustomtools', 'items': [
# put the name of your editor.ui.addButton here
'Preview',
'Maximize',
'CodeSnippet',
'Youtube',
]},
],
'toolbar': 'YourCustomToolbarConfig', # put selected toolbar config here
# 'toolbarGroups': [{ 'name': 'document', 'groups': [ 'mode', 'document', 'doctools' ] }],
# 'height': 291,
# 'width': '100%',
# 'filebrowserWindowHeight': 725,
# 'filebrowserWindowWidth': 940,
# 'toolbarCanCollapse': True,
# 'mathJaxLib': '//cdn.mathjax.org/mathjax/2.2-latest/MathJax.js?config=TeX-AMS_HTML',
'tabSpaces': 4,
'extraPlugins': ','.join([
'uploadimage', # the upload image feature
# your extra plugins here
'div',
'autolink',
'autoembed',
'embedsemantic',
'autogrow',
# 'devtools',
'widget',
'lineutils',
'clipboard',
'dialog',
'dialogui',
'elementspath',
'codesnippet',
'widget',
'dialog',
'youtube',
]),
},
}
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('base.urls')),
# here
path('ckeditor/', include(
'ckeditor_uploader.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
There are two types of model fields RichTextField
and RichTextUploadingField
. The RichTextField
only adds a rich text editor without image uploader while RichTextUploadingField
field adds a rich text editor with image uploader.
To use RichTextField
or RichTextUploadingField
replace models.TextField()
with RichTextField
or RichTextUploadingField
field.
models.py
from django.db import models
from ckeditor_uploader.fields import *
from django.utils.text import slugify
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True, default='1',help_text="Slug will be generated
automatically from the title of the post")
content = RichTextUploadingField()
pub_date = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
views.py
from .models import Post
from django.shortcuts import render, redirect
def post_list(request):
mypost=Post.objects.all()
resp = render(request=request,
template_name='topics.html',
context={"tutorial": mypost})
Rendering CKEditor outside of Django Admin
topics.html
{% load static %}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script>
<script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script>
<link href="{% static 'ckeditor/ckeditor/plugins/codesnippet/lib/highlight/styles/atelier-seaside.dark.css' %}"rel="stylesheet">
<script src="{% static 'ckeditor/ckeditor/plugins/codesnippet/lib/highlight/highlight.pack.js' %}"></script>
<script>hljs.initHighlightingOnLoad();</script>
{{tutorial.content|safe}}
Run migrations:
python manage.py makemigrations
python manage.py migrate
after migrations we can see Ckeditor in django admin,in topics.html we can see the content what ever we type and save in ckeditor,in this tutorial user can add code,images
Image thumbnail in django
March 27, 2020, 9:58 a.m.
257Image Thumbnail in django
Install the following packages:
pip install pillow
pip install django-imagekit
pip install django
django-admin startproject mysite
python manage.py startapp blog
models.py
from django.db import models
from imagekit.models import ImageSpecField
from pilkit.processors import ResizeToFill
class Post(models.Model):
image = models.ImageField(default='',
blank=True,
upload_to='images')
image_medium = ImageSpecField(source='image',
processors=[ResizeToFill(250, 150)],
format='JPEG',
options={'quality': 60})
image_small = ImageSpecField(source='image',
processors=[ResizeToFill(100, 50)],
format='JPEG',
options={'quality': 60})
settings.py
INSTALLED_APPS = [
# ...
'imagekit'
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
admin.py
from django.contrib import admin
from blog.models import Post
admin.site.register(Post)
views.py
from django.shortcuts import render, get_object_or_404
from blog.models import Post
def detail(request, pk=None):
post = get_object_or_404(Post, pk=pk)
return render(request,
'detail.html',
{'post': post})
templates/details.html
{% if post.image %}
<img src="{{ post.image.url }}">
<br><br>
<img src="{{ post.image_medium.url }}">
<img src="{{ post.image_small.url }}">
{% endif %}
urls.py
from django.conf.urls.static import static # HERE
from django.contrib import admin
from django.urls import path
import blog.views # HERE
from mysite import settings # HERE
urlpatterns = [
# HERE
path('blog/<int:pk>/',
blog.views.detail,
name='blog_detail'),
path('admin/', admin.site.urls),
# HERE
] + static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
Run migrations:
python manage.py makemigrations
python manage.py migrate
How to add tags to your models in django
March 7, 2020, 2:05 p.m.
485How to add tags to your models in Django
Categories and tags help you organize your web site or blog and help your users find the information they want. A blog category is a topic you address on your blog. Your category list is like the table of contents for your blog. A tag is more specific and addresses items you discuss in a particular blog post. A tag is usually only a word or two and reflects the keywords or points of your article. If categories are your blog’s table of contents, tags are your blog’s index. By tagging an article with relevant key words, user can find the information easily so it makes your blog more professional.
django-taggit is a reusable application that primarily offers you a Tag model, and a manager for easily adding tags to any model. We will create very simple blog app and implement tagging system in it.
I am assuming that you already created Django project. Let's Start with installing package by following command:
pip install django-taggit
settings.py
INSTALLED_APPS = [
...
'taggit'
]
models.py
from django.db import models
from taggit.managers import TaggableManager
class Post(models.Model):
title = models.CharField(max_length=250)
description = models.TextField()
published = models.DateField(auto_now_add=True)
slug = models.SlugField(unique=True, max_length=100)
tags = TaggableManager()
def __str__(self):
return self.title
The TaggableManager will show up automatically as a field in a ModelForm or in the admin. Tags input via the form field are parsed as follows:
- If the input doesn’t contain any commas or double quotes, it is simply treated as a space-delimited list of tag names.
- If the input does contain either of these character
- Groups of characters which appear between double quotes take precedence as multi-word tags (so doublequoted tag names may contain commas). An unclosed double quote will be ignored.
- Otherwise, if there are any unquoted commas in the input, it will be treated as comma-delimited. If not, itwill be treated as space-delimited.
forms.py
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = [
'title',
'description',
'tags',
]
views.py
from django.shortcuts import render, get_object_or_404
from django.template.defaultfilters import slugify
from .models import Post
from .forms import PostForm
from taggit.models import Tag
def home_view(request):
posts = Post.objects.order_by('-published')
# Show most common tags
common_tags = Post.tags.most_common()[:4]
form = PostForm(request.POST)
if form.is_valid():
newpost = form.save(commit=False)
newpost.slug = slugify(newpost.title)
newpost.save()
# Without this next line the tags won't be saved.
form.save_m2m()
context = {
'posts':posts,
'common_tags':common_tags,
'form':form,
}
return render(request, 'home.html', context)
def detail_view(request, slug):
post = get_object_or_404(Post, slug=slug)
context = {
'post':post,
}
return render(request, 'detail.html', context)
def tagged(request, slug):
tag = get_object_or_404(Tag, slug=slug)
# Filter posts by tag name
posts = Post.objects.filter(tags=tag)
context = {
'tag':tag,
'posts':posts,
}
return render(request, 'home.html', context)
When saving a form, you have to use the commit=False option and call save_m2m() on the form after you save the object.
We are using slugify to convert our post title (string) to valid slug.
As you see you can filter posts by tag name and display most used tags.
templates/base.html
<html>
<head>
<title>Simple Blog</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" >
<link rel="stylesheet" href="/static/css/tagsinput.css" />
</head>
<body>
{% block content %}{% endblock content %}
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" ></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" ></script>
<script src="/static/js/tagsinut.js"></script>
<script>
$("#post-form").submit(function(e){
e.preventDefault();
});</script>
</body>
</html>
templates/home.html
{% extends 'base.html' %}
{% block content %}
<div class="container pt-5">
<form method="POST">
{% csrf_token %}
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" name="title" placeholder="Add title">
</div>
<div class="form-group">
<label>Description</label>
<textarea type="text" class="form-control" name="description" placeholder="Add description"></textarea>
</div>
<div class="form-group">
<label>Tags</label>
<input type="text" data-role="tagsinput" class="form-control" name="tags">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<p>Common Tags:
{% for mt in common_tags %}
<a href="#" class="badge badge-success">{{mt}}</a>
{% endfor %}
</p>
<div class="row mb-2 posts">
{% for post in posts %}
<div class="col-md-6">
<div class="cards">
<div class="row no-gutters border rounded flex-md-row mb-4 shadow-sm h-md-250">
<div class="col p-4 d-flex flex-column position-static">
<h3 class="my-1"><a href="{% url 'detail' post.slug %}">{{post.title}}</a></h3>
<div style="display:flex">
{% for tag in post.tags.all %}
<a href="{% url 'tagged' tag.slug %}" class="mr-1 badge badge-info">#{{ tag }}</a>
{% endfor %}
</div>
<p class="mb-auto">{{post.description}}</p>
<p class="mb-auto text-muted">{{post.published}}</p>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock content %}
we are done.
Check documentation of django-taggit for more.
Most useful meta tags for every website
March 5, 2020, 9:03 a.m.
267Most useful meta tags for every website
Basic HTML Meta Tags
<meta name="keywords" content="your, tags"/>
<meta name="description" content="150 words" />
<meta name="subject" content="your website's subject ">
<meta name="copyright"content="company name ">
<meta name="language" content="ES ">
<meta name="robots" content="index,follow" />
<meta name="revised" content="Sunday, July 18th, 2010, 5:15 pm" />
<meta name="abstract" content=" ">
<meta name="topic" content=" ">
<meta name="summary" content=" ">
<meta name="Classification" content="Business ">
<meta name="author" content="name, [email protected] ">
<meta name="designer" content=" ">
<meta name="copyright" content=" ">
<meta name="reply-to" content="[email protected] ">
<meta name="owner" content=" ">
<meta name="url" content="http://www.websiteaddrress.com ">
<meta name="identifier-URL" content="http://www.websiteaddress.com ">
<meta name="directory" content="submission ">
<meta name="category" content=" ">
<meta name="coverage" content="Worldwide ">
<meta name="distribution" content="Global ">
<meta name="rating" content="General ">
<meta name="revisit-after" content="7 days ">
<meta http-equiv="Expires" content="0 ">
<meta http-equiv="Pragma" content="no-cache ">
<meta http-equiv="Cache-Control" content="no-cache ">
OpenGraph Meta Tags
<meta name="og:title" content="The Rock" />
<meta name="og:type" content="movie" />
<meta name="og:url" content="http://www.imdb.com/title/tt0117500/" />
<meta name="og:image" content="http://ia.media-imdb.com/rock.jpg" />
<meta name="og:site_name" content="IMDb" />
<meta name="og:description" content="A group of U.S. Marines, under command of..." />
<meta name="fb:page_id" content="43929265776" />
<meta name="og:email" content="[email protected]" />
<meta name="og:phone_number" content="650-123-4567" />
<meta name="og:fax_number" content="+1-415-123-4567" />
<meta name="og:latitude" content="37.416343" />
<meta name="og:longitude" content="-122.153013" />
<meta name="og:street-address" content="1601 S California Ave" />
<meta name="og:locality" content="Palo Alto" />
<meta name="og:region" content="CA" />
<meta name="og:postal-code" content="94304" />
<meta name="og:country-name" content="USA" />
<meta property="og:type" content="game.achievement" />
<meta property="og:points" content="POINTS_FOR_ACHIEVEMENT" />
<meta property="og:video" content="http://example.com/awesome.swf" />
<meta property="og:video:height" content="640" />
<meta property="og:video:width" content="385" />
<meta property="og:video:type" content="application/x-shockwave-flash" />
<meta property="og:video" content="http://example.com/html5.mp4" />
<meta property="og:video:type" content="video/mp4" />
<meta property="og:video" content="http://example.com/fallback.vid" />
<meta property="og:video:type" content="text/html" />
<meta property="og:audio" content="http://example.com/amazing.mp3" />
<meta property="og:audio:title" content="Amazing Song" />
<meta property="og:audio:artist" content="Amazing Band" />
<meta property="og:audio:album" content="Amazing Album" />
<meta property="og:audio:type" content="application/mp3" />
Create Custom Meta Tags
Use custom meta tags to store data that you need in javascript, instead of hard-coding that data into your javascript. I store my Google Analytics code in meta tags. Here's some examples:
<meta name="google-analytics" content="1-AHFKALJ" />
<meta name="disqus" content="abcdefg" />
<meta name="uservoice" content="asdfasdf" />
<meta name="mixpanel" content="asdfasdf" />
Company/Service Meta Tags
ClaimID
<meta name="microid" content="mailto+http:sha1:e6058ed7fca4a1921cq91d7f1f3b8736cd3cc1g7" />
Apple Meta Tags
<meta name="apple-mobile-web-app-capable" content="yes ">
<meta content="yes" name="apple-touch-fullscreen" />
<meta name="apple-mobile-web-app-status-bar-style" content="black ">
<meta name="format-detection" content="telephone=no ">
<meta name="viewport" content="width = 320, initial-scale = 2.3, user-scalable = no ">
Internet Explorer Meta Tags
<meta http-equiv="Page-Enter" content="RevealTrans(Duration=2.0,Transition=2)" />
<meta http-equiv="Page-Exit" content="RevealTrans(Duration=3.0,Transition=12)" />
<meta name="mssmarttagspreventparsing" content="true ">
<meta http-equiv="X-UA-Compatible" content="chrome=1 ">
<meta name="msapplication-starturl" content="http://blog.reybango.com/about/" />
<meta name="msapplication-window" content="width=800;height=600" />
<meta name="msapplication-navbutton-color" content="red" />
<meta name="application-name" content="Rey Bango Front-end Developer" />
<meta name="msapplication-tooltip" content="Launch Rey Bango's Blog" />
<meta name="msapplication-task" content="name=About;action-uri=/about/;icon-uri=/images/about.ico" />
<meta name="msapplication-task" content="name=The Big List;action-uri=/the-big-list-of-javascript-css-and-html-development-tools-libraries-projects-and-books/;icon-uri=/images/list_links.ico" />
<meta name="msapplication-task" content="name=jQuery Posts;action-uri=/category/jquery/;icon-uri=/images/jquery.ico" />
<meta name="msapplication-task" content="name=Start Developing;action-uri=/category/javascript/;icon-uri=/images/script.ico" />
<link rel="shortcut icon" href="/images/favicon.ico" />
TweetMeme Meta Tags
<meta name="tweetmeme-title" content="Retweet Button Explained" />
Blog Catalog Meta Tags
<meta name="blogcatalog" />
Rails Meta Tags
<meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="/bZVwvomkAnwAI1Qd37lFeewvpOIiackk9121fFwWwc=" />
Apple Tags
<meta name="apple-mobile-web-app-capable" content="yes ">
<meta name="apple-mobile-web-app-status-bar-style" content="black ">
<meta name="format-detection" content="telephone=no ">
<meta name= "viewport" content = "width = 320, initial-scale = 2.3, user-scalable = no ">
<meta name= "viewport" content = "width = device-width ">
<meta name = "viewport" content = "initial-scale = 1.0 ">
<meta name = "viewport" content = "initial-scale = 2.3, user-scalable = no ">
<link rel="apple-touch-icon" href="touch-icon-iphone.png" />
<link rel="apple-touch-icon" sizes="72x72" href="touch-icon-ipad.png" />
<link rel="apple-touch-icon" sizes="114x114" href="touch-icon-iphone4.png" />
<link rel="apple-touch-startup-image" href="/startup.png ">
<link rel="apple-touch-icon" type="image/png" href="/apple-touch-icon.png" />
HTML Link Tags
<link rel="alternate" type="application/rss+xml" title="RSS" href="http://feeds.feedburner.com/martini" />
<link rel="shortcut icon" type="image/ico" href="/favicon.ico" />
<link rel="fluid-icon" type="image/png" href="/fluid-icon.png" />
<link rel="me" type="text/html" href="http://google.com/profiles/thenextweb" />
<link rel='shortlink' href='http://blog.unto.net/?p=353' />
<link rel='archives' title='May 2003' href='http://blog.unto.net/2003/05/' />
<link rel='index' title='DeWitt Clinton' href='http://blog.unto.net/' />
<link rel='start' title='Pattern Recognition 1' href='http://blog.unto.net/photos/pattern_recognition_1_about/' />
<link rel='prev' title='OpenSearch and OpenID? A sure way to get my attention.' href='http://blog.unto.net/opensearch/opensearch-and-openid-a-sure-way-to-get-my-attention/' />
<link rel='next' title='Not blog' href='http://blog.unto.net/meta/not-blog/' />
<link rel="search" href="/search.xml" type="application/opensearchdescription+xml" title="Viatropos" />
<link rel="self" type="application/atom+xml" href="http://www.syfyportal.com/atomFeed.php?page=3" />
<link rel="first" href="http://www.syfyportal.com/atomFeed.php" />
<link rel="next" href="http://www.syfyportal.com/atomFeed.php?page=4" />
<link rel="previous" href="http://www.syfyportal.com/atomFeed.php?page=2" />
<link rel="last" href="http://www.syfyportal.com/atomFeed.php?page=147" />
<link rel='shortlink' href='http://smallbiztrends.com/?p=43625' />
<link rel="canonical" href="http://smallbiztrends.com/2010/06/9-things-to-do-before-entering-social-media.html" />
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://smallbiztrends.com/xmlrpc.php?rsd" />
<link rel="pingback" href="http://smallbiztrends.com/xmlrpc.php" />
<link media="only screen and (max-device-width: 480px)" href="http://wordpress.org/style/iphone.css" type="text/css" rel="sstylesheet" />
this viewport settings is to allow device height and width pipe down into the CSS, the minimal-ui is suitable for old iOS devices but it is an old definition that is no longer used in newer devices,
so it is placed near the end. If you want to allow the user to scale the page remove user-scalable=no and maximum-scale=1.0.
<meta name="viewport" content="height=device-height,width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no,minimal-ui"/>
robots rule that allows all variation of Google indexing, including Google translate and image archive, including indexing the web-pages in open-directory
<meta name="robots" content="archive,follow,imageindex,index,odp,snippet,translate"/>
this is new stuff, allowing the web-page and content to be served from cache even if the case is stale (old) provided that the web-page hasn't changed, it can speed the loading a lot. the rem attribute is a 'remark' to help to remember- optional.
<meta http-equiv="Cache-Control" content="public,max-age=1800,max-stale,stale-while-revalidate=86400,stale-if-error=259200" rem="max-age=30minutes"/>
preloading resources is done in another low-priority thread, you should definitely use it,
<link rel="preload" as="script" crossorigin="anonymous" type="application/js" charset="UTF-8" href="index.js"/>
<link rel="preload" as="style" crossorigin="anonymous" type="text/css" charset="UTF-8" href="index.css"/> ...... ...... <link rel="stylesheet" media="all" crossorigin="anonymous" type="text/css" charset="UTF-8" href="index.css"/>
</head> ..... .... <script defer crossorigin="anonymous" type="application/javascript" charset="UTF-8" src="index.js"></script> </body>
feature control if you need to use those features you can explicitly allow them
<meta http-equiv="Feature-Policy"content='{"vibrate":["*"],"geolocation":["*"],"fullscreen":["*"]}'/>
force Google to render your page including javascript before crawling it.
- if your page is mainly js-logic operated, this way you won't get a blank page with web-crawlers.
- <meta name="fragment" content="!"/>
- declare that your website is family-safe
- <meta name="target" content="all"/>
- <meta name="audience" content="all"/>
- <meta name="coverage" content="Worldwide"/>
- <meta name="distribution" content="Global">
- <meta name="og:type" content="website"/>
- <meta name="rating" content="safe for kids"/>
- disabling all of the custom formats, IE toolbars and skype. for skype you MUST use exactly as shown here:
- <meta name="SKYPE_TOOLBAR" content="SKYPE_TOOLBAR_PARSER_COMPATIBLE"> no extra spaces no letter-case change. <meta name="format-detection" content="telephone=no,date=no,address=no,email=no,url=no" />
- <meta name="SKYPE_TOOLBAR" content="SKYPE_TOOLBAR_PARSER_COMPATIBLE">
- <meta name="mssmarttagspreventparsing" content="true" />
- <meta http-equiv="imagetoolbar" content="no" />
- allow smooth fade-in and declare the web-page is mobile-friendly:
- <meta name="HandheldFriendly" content="True" />
- <meta name="MSThemeCompatible" content="no" />
- <meta name="apple-mobile-web-app-capable" content="yes" />
- <meta name="apple-mobile-web-app-status-bar-style" content="translucent black" />
- <meta name="msapplication-navbutton-color" content="translucent black" />
- <meta name="mssmarttagspreventparsing" content="true" />
- <meta name="theme-color" content="#b1cff4" />
- <meta http-equiv="Page-Enter" content="RevealTrans(Duration=1.0,Transition=1)" />
- <meta http-equiv="Page-Exit" content="RevealTrans(Duration=1.0,Transition=1)" />
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
- <meta http-equiv="refresh" content="30" />
- <meta name="target" content="all" />
- <meta name="audience" content="all" />
- <meta name="coverage" content="Worldwide" />
- <meta name="distribution" content="Global">
- <meta name="og:type" content="website" />
- <meta name="rating" content="safe for kids" />
- to make everything work you must declare doctype and prefix in the HTML node for example:
- <!doctype html>
- <html encoding="UTF-8" charset="UTF-8" dir="ltr" lang="en-US" language="English" prefix="og: http://ogp.me/ns#" itemtype="http://schema.org/WebPage">
Deploying a django application in server/production
Feb. 24, 2020, 12:21 a.m.
290Deploying a Django application in server/production
A Unix server for deploying the app , connected with a SSH(preferred).
Django is a free and open source web application framework, written in Python. Django has a lot of inbuilt set of components that helps you to develop websites faster and easier.
Gunicorn is a simple, light-weight Python WSGI HTTP Server for UNIX. WSGI is the Web Server Gateway Interface. It is a specification that describes how a web server communicates with web applications, and how web applications can be chained together to process one request.
Nginx is a high-performance HTTP server, reverse proxy, load balancer and static files loader.
Supervisord is a process-control system which allows us to monitor and control a number of processes on UNIX operating system.
Let’s start with our server
Once we create our server and let’s login to the server via SSH,
$ ssh [email protected]_ADDRESS_OF_SERVER
Now we have to install the prerequisites, run these commands
$ sudo apt-get update
$ sudo apt-get install git python-pip python-dev virtualenv virtualenvwrapper
$ sudo apt-get install postgresql postgresql-contrib
$ pip install --upgrade pip
Now let’s configure the virtual-env wrapper
After setting-up the virtualenvwrapper, create a virtualenv
$ mkvirtualenv env-name
From within our virtual-env, install:
(env-name) $ pip install django gunicorn psycopg2
Let’s clone the repo in home folder, pull the application from Git, we use this repo https://github.com/kwikl3arn/django-demo
$ cd ~
$ git clone https://github.com/kwikl3arn/django-demo
Now we have to add permissions to the manage.py
file
$ cd /django-demo/
$ chmod 755 manage.py
Now install the requirements
(env-name) $ pip install -r requirements.txt
Now set up PostgreSQL
Create a file .env
and add these lines in that
$ export POSTGRES_DB = pollsdb
$ export POSTGRES_USER = polls_admin
$ export POSTGRES_PASSWORD = polls_password
$ export POLLSAPI_PG_HOST = 127.0.0.1
Create a postgres Database
$ sudo -u postgres psql
After running the above command, we will be logged inside PostgreSQL terminal, now lets create our db and user
> CREATE DATABASE pollsdb;
> CREATE USER polls_admin WITH PASSWORD 'polls_password';
> ALTER ROLE polls_admin SET client_encoding TO 'utf8';
> ALTER ROLE polls_admin SET default_transaction_isolation TO 'read committed';
> ALTER ROLE polls_admin SET timezone TO 'UTC';
> ALTER USER polls_admin CREATEDB;
> GRANT ALL PRIVILEGES ON DATABASE pollsdb TO polls_admin;
> \q # to quit the shell
Make sure that these details match the details in the .env
file. Exit the PostgreSQL shell by typing \q
.
Now as the DB is ready , we can run migrations command inside the repo folder.
# migrations
(env-name) $ python manage.py migrate
# Create a supervisor, let's
(env-name) $ python manage.py createsuperuser
Now postgres-db is setted, now we have to set up the server
Using gunicorn
(env-name) $ pip install gunicorn
After installing gunicorn , now run it
# starts the server
(env-name) $ gunicorn polls_rest.wsgi
It will run the app , we can check IP_ADDRESS_OF_SERVER:8000
, IP_ADDRESS_OF_SERVER:8000/admin
. It will not have any css , as the gunicorn only serves the application. We will be serving static files using nginx .
To exit it press Ctrl+C
.
# starts the server by binding it to a specific port
(env-name) $ gunicorn --bind 0.0.0.0:8888 polls_rest.wsgi
# running with a config file
(env-name) $ gunicorn -c /path/to/config/file polls_rest.wsgi
# running in daemon mode
(env-name) $ gunicorn --daemon polls_rest.wsgi
If it is in daemon-mode, then exit it with pkill gunicorn
, which will kill the gunicorn process.
To have a gunicorn config file for gunicorn , we write the config file in a .py
.
Using nginx
By using gunicorn, we were able to run the application, but without styles as the gunicorn only runs the application and does not serve the static files django does not serve static file except in development.
We will use nginx
to serve the static files , nginx will first get the request, and it will send it to gunicorn.
To install nginx
$ sudo apt-get install nginx
let’s configure nginx
So, create a file /etc/nginx/sites-available/pollsapp
and add the following
server {
listen 80; #L1
server_name SERVER_DOMAIN_OR_IP_ADDRESS_OF_SERVER; #L2
location = /favicon.ico { access_log off; log_not_found off; } #L3
location /static/ { #L4
root /home/django-polls-rest;
}
location / { #l5
include proxy_params;
proxy_pass http://unix:/home/django-polls-rest/polls_rest.sock;
}
}
- #L1 and #L2 lines defines where our nginx server should run.
- #L3 line ignores any errors related to the favicon.
- #L4 block
location /static/
defines the location of static files. - #L5 block
location /
tells the socket(gunicorn socket) to communicate.
After this, we have to enable this config file by linking with the sites-enabled
folder.
$ ln -s /etc/nginx/sites-available/pollsapp /etc/nginx/sites-enabled
We link the above file to sites-enabled
, so that it will be included in the main nginx settings file /etc/nginx/nginx.conf
After enabling the config file , we can check nginx configuration by
$ sudo nginx -t
If the configuration file is correct , then we should see this
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nging: configuration file /etc/nginx/nginx.conf test is successful
Now we have to mention the static files directory of our app in settings.py
file . So add this line in settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
After adding this line, we have to perform run collectstatic
command
(env-name) $ python manage.py collectstatic
Let’s run the app
(env-name) $ gunicorn --daemon --workers 3 --bind unix:/home/django-polls-rest/polls_rest.sock polls_rest.wsgi
The /home/django-polls-rest/polls_rest.sock
file is a unix-socket file which will be created automatically. And this file will enable Gunicorn and Nginx to communicate with each other.
Now Restart Nginx for changes to take effect.
$ sudo service nginx restart
This will run our app in the http://IP_ADDRESS
Point to remember , check
ALLOWED_HOSTS
insettings.py
to have you host name or ip address of server.
Configuring Gunicorn with Supervisord
Supervisor is a process monitoring tool, which can restart any process if the process dies or gets killed for some reason.
At present we are manually starting gunicorn in daemon to run our app, Suppose if this gunicorn process closes or gets killed due to some reason then we have to manually start it again. To monitor our processes we use Supervisord, So that supervisor controls the gunicorn process.
To install supervisord
$ sudo apt-get install supervisor
Let’s add a configuration file pollsapi.conf
for our application in /etc/supervisor/conf.d/
folder, the conf.d
folder will have all our config files.
[program:pollsapi] #L1
directory=/home/django-polls-rest/polls_rest #L2
command=/home/.virtualenvs/demo-polls-1/bin/gunicorn --workers 3 --bind unix:/home/django-polls-rest/polls_rest.sock polls_rest.wsgi #L3
autostart=true #L4
autorestart=true #L5
stderr_logfile=/var/log/pollsapi.err.log #L6
stdout_logfile=/var/log/pollsapi.out.log #L7
Let’s understand the config file we have written,
- #L1 line
[program:pollsapi]
names the program( or process ) as pollsapi, which can be used as
$ sudo supervisorctl start pollsapi
- #L2 line
directory
is the path to our project. - #L3 line
command
is the command to start our project - #L4 lines
autostart
tells the script to start on system boot. - #L5 line
autorestart
tells the script to restart when it closes for some reason - #L6
stderr_logfile
which will store the error logs & #L7stdout_logfile
will store the non-error logs.
Now lets save this file and update supervisor
$ sudo supervisorctl reread
$ sudo supervisorctl update
$ sudo supervisorctl reload
Check the supervisor status .
$ sudo supervisorctl status
This will show
gunicorn RUNNING pid 1651, uptime:0:00:23
To check gunicorn processes
$ ps ax | grep gunicorn
This command lists all the processes running with gunicorn
To check if the app is running , let’s do curl
$ curl 0.0.0.0:8000
After configuring gunicorn with supervisor, let’s restart our nginx
$ systemctl restart nginx
Now our app should be running on http://IP_ADDRESS_OF_SERVER
How to remove app name while creating a new table in django
Feb. 24, 2020, 12:01 a.m.
226How to remove app name while creating a new table in django
To save you time, Django automatically derives the name of the database table from the name of your model class and the app that contains it. A model’s database table name is constructed by joining the model’s “app label” – the name you used in manage.py startapp – to the model’s class name, with an underscore between them.
We have two apps in our demo application i.e., heros
and devils
so all the models in them will have app names as the prefixes followed by _ then the model name.
hero_origin
hero_type
hero_country
devil_name
devil_type
For renaming them we cab use db_table
parameter
models.py
class TempUser(models.Model):
first_name = models.CharField(max_length=100)
. . .
class Meta:
db_table = "temp_user"
if we make migrations and check the databse we can see table name temp_user,with out app name
How to reload a model object from the database in django
Feb. 23, 2020, 11:49 p.m.
280How to reload a model object from the database in django
Models can be reloaded from the databse using refresh_from_db()
method. THis proves helpful during testing. For example.
class TestORM(TestCase):
def test_update_result(self):
userobject = User.objects.create(username='testuser', first_name='Test', last_name='user')
User.objects.filter(username='testuser').update(username='test1user')
# At this point userobject.val is still testuser, but the value in the database
# was updated to test1user. The object's updated value needs to be reloaded
# from the database.
userobject.refresh_from_db()
self.assertEqual(userobject.username, 'test1user')
How to perform truncate like operation using django orm
Feb. 23, 2020, 11:44 p.m.
449How to perform truncate like operation using Django ORM
Truncate statement in SQL is meant to empty a table for future use. Though Django doesn’t provide a builtin to truncate a table, but still similar result can be achived using delete()
method. For example:
>>> Category.objects.all().count()
7
>>> Category.objects.all().delete()
(7, {'entity.Category': 7})
>>> Category.objects.all().count()
0
This works, but this uses DELETE FROM ...
SQL statement. If you have a large number of records, this can be quite slow. You can add a classmethod
to Category
if you want to enable truncate
.
models.py
class Category(models.Model):
# ...
@classmethod
def truncate(cls):
with connection.cursor() as cursor:
cursor.execute('TRUNCATE TABLE "{0}" CASCADE'.format(cls._meta.db_table))
Then you can call Category.truncate()
to a real database truncate.
How to specify the column name for model field in django
Feb. 23, 2020, 11:33 p.m.
171How to specify the column name for model field in django
Naming of a column in the model can be achieved py passing a db_column
parameter with some name. If we don’t pass this parameter django creates a column with the field name which we give
class ColumnName(models.Model):
ironman = models.CharField(max_length=40,db_column='column1')
column2 = models.CharField(max_length=50)
def __str__(self):
return self.a
Above we can db_column
has higher priority over field name
. First column is named as column1 but not as ironamn.
How to use slug field with django for more readability
Feb. 23, 2020, 11:22 p.m.
191How to use slug field with django for more readability
Slug is a part of a URL which identifies a particular page on a website in a form readable by users. For making it work django offers us a slugfield. It can be implimented as under. We already had a model Article
we will be adding slugfield to it to make it user readable.
from django.utils.text import slugify
class Article(models.Model):
headline = models.CharField(max_length=100)
. . .
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.headline)
super(Article, self).save(*args, **kwargs)
. . .
type below code in shell
>>> u1 = User.objects.get(id=1)
>>> from datetime import date
>>> a1 = Article.objects.create(headline="how to use slug", pub_date=date(2020, 2, 23), reporter=u1)
>>> a1.save()
// slug here is auto-generated, we haven't created it in the above create method.
>>> a1.slug
'how-to-use-slug'
Slug is useful because:
it’s human friendly (eg. /blog/ instead of /1/).
it’s good SEO to create consistency in title, heading and URL.
Creating django models of an existing data base
Feb. 23, 2020, 11:10 p.m.
185Creating Django models of an existing data base
Django comes with a utility called inspectdb
that can create models by introspecting an existing database. You can view the output by running this command
python manage.py inspectdb
Befor running this you will have to configure your database in the settings.py
file. The result will be a file containing a model for each table. You may want to save that file
python manage.py inspectdb > models.py
The output file will be saved to your current directory. Move that file to the correct app and you have a good starting point for further customizations.
eg: For specific table from specific database()
python manage.py inspectdb Employee_table --database=db_for_employee > models_file.py
Here db_for_employee exist in DATABASE list in settings.py file.
For specific table in default database:
python manage.py inspectdb Employee_table > models_file.py
For all the tables in default database:
python manage.py inspectdb >models_file.py
This would create a file with name models_file.py at your project level and it would contain the models for the existing database.
Note that the if you don't mention the database name then default database from the settings would be considered.
And if you don't mention the table name then all the tables from the database are considered and you'll find models for all the tables in new models.py file
Needless to say that further you'll have to copy the models or the classes created, to the actual models.py file at the application level.
How to reset django admin password?
Feb. 23, 2020, 11:01 p.m.
185How to reset Django admin password?
If you forogot your super admin password,you can simply reset that by useing below command.
method1:
python manage.py changepassword <user_name>
python manage.py changepassword ironman # here ironman is my user name for superadmin
method2:
python manage.py shell
then use following script in shell
from django.contrib.auth.models import User
User.objects.filter(is_superuser=True)
will list you all super users on the system. if you recognize yur username from the list
usr = User.objects.get(username='your username')
usr.set_password('raw password')
usr.save()
and you set a new password.
Transactions in django
Feb. 16, 2020, 9:14 a.m.
192Transactions in django
By default, Django immediately commits changes to the database. When exceptions occur during a series of commits, this can leave your database in an unwanted state:
def create_category(name, products):
category = Category.objects.create(name=name)
product_api.add_products_to_category(category, products)
activate_category(category)
In the following scenario:
>>> create_category('clothing', ['shirt', 'trousers', 'tie'])
---------------------------------------------------------------------------
ValueError: Product 'trousers' already exists
An exception occurs whilst trying to add the trousers product to the clothing category. By this point, the category itself has already been added, and the shirt product has been added to it.
The incomplete category and containing product would have to be manually removed before fixing the code and calling the create_category()
method once more, as otherwise a duplicate category would be created.
Solution
[a] series of database operations such that either all occur, or nothing occurs.
The django.db.transaction
module allows you to combine multiple database changes into an atomic transaction:
Applied to the above scenario, this can be applied as a decorator:
from django.db import transaction
@transaction.atomic
def create_category(name, products):
category = Category.objects.create(name=name)
product_api.add_products_to_category(category, products)
activate_category(category)
Or by using a context manager:
def create_category(name, products):
with transaction.atomic():
category = Category.objects.create(name=name)
product_api.add_products_to_category(category, products)
activate_category(category)
Now, if an exception occurs at any stage within the transaction, no database changes will be committed.
Autocomplete in django admin
Feb. 16, 2020, 9:09 a.m.
258Autocomplete in django admin
By default, Django renders ForeignKey
fields as a <select>
input. This can cause pages to be load really slowly if you have thousands or tens of thousand entries in the referenced table. And even if you have only hundreds of entries, it is quite uncomfortable to look for a particular entry among all.
A very handy external module for this is django-autocomplete-light (DAL). This enables to use autocomplete fields instead of <select>
fields.
views.py
from dal import autocomplete
class CityAutocomp(autocomplete.Select2QuerySetView):
def get_queryset(self):
qs = City.objects.all()
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
urls.py
urlpatterns = [
path('city-autocomp/', CityAutocomp.as_view(), name='city-autocomp'),
]
forms.py
from dal import autocomplete
class PlaceForm(forms.ModelForm):
city = forms.ModelChoiceField(
queryset=City.objects.all(),
widget=autocomplete.ModelSelect2(url='city-autocomp')
)
class Meta:
model = Place
fields = ['__all__']
admin.py
@admin.register(Place)
class PlaceAdmin(admin.ModelAdmin):
form = PlaceForm
Using base_dir to ensure app portability
Feb. 16, 2020, 9 a.m.
188Using BASE_DIR to ensure app portability
It's a bad idea to hard code paths in your application. One should always use relative urls so that your code can work seamlessly across different machines. The best way to set this up is to define a variable like this.
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
Then use this BASE_DIR
variable to define all your other settings.
settings.py
TEMPLATE_PATH = os.path.join(BASE_DIR, "templates")
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
And so on. This ensures that you can port your code across different machines without any worries.
However, os.path
is a bit verbose. For instance if your settings module is project.settings.dev
, you will have to write:
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
An alternative is to use the unipath
module
pip install unipath
from unipath import Path
BASE_DIR = Path(__file__).ancestor(2) # or ancestor(3) if using a submodule
TEMPLATE_PATH = BASE_DIR.child('templates')
STATICFILES_DIRS = [
BASE_DIR.child('static'),
]
Hiding secret data using a json file in django
Feb. 16, 2020, 8:54 a.m.
181Hiding secret data using a JSON file in django
When using a VCS such as Git or SVN, there are some secret data that must never be versioned (whether the repository is public or private).
Among those data, you find the SECRET_KEY
setting and the database password.
A common practice to hide these settings from version control is to create a file secrets.json
at the root of your project (thanks "Two Scoops of Django" for the idea):
secrets.json
{
"SECRET_KEY": "N4HE:AMk:.Ader5354DR453TH8SHTQr",
"DB_PASSWORD": "v3ry53cr3t"
}
And add it to your ignore list (.gitignore
for git):
.gitignore
*.py[co]
*.sw[po]
*~
/secrets.json
Then add the following function to your settings
module:
settings.py
import json
import os
from django.core.exceptions import ImproperlyConfigured
with open(os.path.join(BASE_DIR, 'secrets.json')) as secrets_file:
secrets = json.load(secrets_file)
def get_secret(setting, secrets=secrets):
"""Get secret setting or fail with ImproperlyConfigured"""
try:
return secrets[setting]
except KeyError:
raise ImproperlyConfigured("Set the {} setting".format(setting))
Then fill the settings this way:
settings.py
SECRET_KEY = get_secret('SECRET_KEY')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgres',
'NAME': 'db_name',
'USER': 'username',
'PASSWORD': get_secret('DB_PASSWORD'),
},
}
Cross-site request forgery (csrf) protection in django
Feb. 16, 2020, 8:47 a.m.
198Cross-site Request Forgery (CSRF) protection
Cross-site request forgery, also known as one-click attack or session riding and abbreviated as CSRF or XSRF, is a type of malicious exploit of a website where unauthorized commands are transmitted from a user that the website trusts. Learn more
To enable CSRF protection, add the CsrfViewMiddleware
to your middleware classes. This middleware is enabled by default.
# settings.py
MIDDLEWARE_CLASSES = [
...
'django.middleware.csrf.CsrfViewMiddleware',
...
]
This middleware will set a token in a cookie on the outgoing response. Whenever an incoming request uses an unsafe method (any method except GET
, HEAD
, OPTIONS
and TRACE
), the cookie must match a token that is send as the csrfmiddlewaretoken
form data or as the X-CsrfToken
header. This ensures that the client initiating the request is also the owner of the cookie and, by extension, the (authenticated) session.
If a request is made over HTTPS
, strict referrer checking is enabled. If the HTTP_REFERER
header does not match the host of the current request or a host in CSRF_TRUSTED_ORIGINS
(new in 1.9), the request is denied.
Forms that use the POST
method should include the CSRF token in the template. The {% csrf_token %}
template tag will output a hidden field, and will ensure that the cookie is set on the response:
<form method='POST'>
{% csrf_token %}
...
</form>
Individual views that are not vulnerable to CSRF attacks can be made exempt using the @csrf_exempt
decorator:
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def my_view(request, *args, **kwargs):
"""Allows unsafe methods without CSRF protection"""
return HttpResponse(...)
Although not recommended, you can disable the CsrfViewMiddleware
if many of your views are not vulnerable to CSRF attacks. In this case you can use the @csrf_protect
decorator to protect individual views:
from django.views.decorators.csrf import csrf_protect
@csrf_protect
def my_view(request, *args, **kwargs):
"""This view is protected against CSRF attacks if the middleware is disabled"""
return HttpResponse(...)
Cross site scripting (xss) protection in django
Feb. 16, 2020, 8:43 a.m.
206Cross Site Scripting (XSS) protection in django
XSS attacks consist in injecting HTML (or JS) code in a page. See What is cross site scripting for more information.
To prevent from this attack, by default, Django escapes strings passed through a template variable.
Given the following context:
context = {
'class_name': 'large" style="font-size:4000px',
'paragraph': (
"<script type=\"text/javascript\">alert('hello world!');</script>"),
}
<p class="{{ class_name }}">{{ paragraph }}</p>
<!-- Will be rendered as: -->
<p class="large" style="font-size: 4000px"><script>alert('hello world!');</script></p>
If you have variables containing HTML that you trust and actually want to render, you must explicitly say it is safe:
<p class="{{ class_name|safe }}">{{ paragraph }}</p>
<!-- Will be rendered as: -->
<p class="large" style="font-size: 4000px"><script>alert('hello world!');</script></p>
If you have a block containing multiple variables that are all safe, you can locally disable auto escaping:
{% autoescape off %}
<p class="{{ class_name }}">{{ paragraph }}</p>
{% endautoescape %}
<!-- Will be rendered as: -->
<p class="large" style="font-size: 4000px"><script>alert('hello world!');</script></p>
You can also mark a string as safe outside of the template:
from django.utils.safestring import mark_safe
context = {
'class_name': 'large" style="font-size:4000px',
'paragraph': mark_safe(
"<script type=\"text/javascript\">alert('hello world!');</script>"),
}
<p class="{{ class_name }}">{{ paragraph }}</p>
<!-- Will be rendered as: -->
<p class="large" style="font-size: 4000px"><script>alert('hello world!');</script></p>
Some Django utilities such as format_html
already return strings marked as safe:
from django.utils.html import format_html
context = {
'var': format_html('<b>{}</b> {}', 'hello', '<i>world!</i>'),
}
<p>{{ var }}</p>
<!-- Will be rendered as -->
<p><b>hello</b> <i>world!</i></p>
Clickjacking protection in django
Feb. 16, 2020, 8:38 a.m.
127Clickjacking protection in django
Clickjacking is a malicious technique of tricking a Web user into clicking on something different from what the user perceives they are clicking on. Learn more
To enable clickjacking protection, add the XFrameOptionsMiddleware
to your middleware classes. This should already be there if you didn't remove it.
settings.py
MIDDLEWARE_CLASSES = [
...
'django.middleware.clickjacking.XFrameOptionsMiddleware',
...
]
This middleware sets the 'X-Frame-Options' header to your all your responses, unless explicitly exempted or already set (not overridden if already set in the response). By default it is set to "SAMEORIGIN". To change this, use the X_FRAME_OPTIONS
setting:
settings.py
X_FRAME_OPTIONS = 'DENY'
You can override the default behaviour on a per-view basis.
views.py
from django.utils.decorators import method_decorator
from django.views.decorators.clickjacking import (
xframe_options_exempt, xframe_options_deny, xframe_options_sameorigin,
)
xframe_options_exempt_m = method_decorator(xframe_options_exempt, name='dispatch')
@xframe_options_sameorigin
def my_view(request, *args, **kwargs):
"""Forces 'X-Frame-Options: SAMEORIGIN'."""
return HttpResponse(...)
@method_decorator(xframe_options_deny, name='dispatch')
class MyView(View):
"""Forces 'X-Frame-Options: DENY'."""
@xframe_options_exempt_m
class MyView(View):
"""Does not set 'X-Frame-Options' header when passing through the
XFrameOptionsMiddleware.
"""
Quickly check if your app is ready for production in django
Feb. 16, 2020, 8:21 a.m.
160Quickly Check If Your App Is Ready For Production in django
Before deploying Your Django app, You need to make sure security, logging and other issues are taken care. Django provides a simple deployment checklist which helps a lot. In development version Django provides --deploy option, which does some security checks. You can run it with
python manage.py check --deploy
I have just created a new project and Django identified 6 security issues in it.
python manage.py check --deploy
System check identified some issues:
WARNINGS:
?: (security.W001) You do not have 'django.middleware.security.SecurityMiddleware' in your MIDDLEWARE_CLASSES so the SECURE_HSTS_SECONDS, SECURE_CONTENT_TYPE_NOSNIFF, SECURE_BROWSER_XSS_FILTER, and SECURE_SSL_REDIRECT settings will have no effect.?: (security.W012) SESSION_COOKIE_SECURE is not set to True. Using a secure-only session cookie makes it more difficult for network traffic sniffers to hijack user sessions.
?: (security.W016) You have 'django.middleware.csrf.CsrfViewMiddleware' in your MIDDLEWARE_CLASSES, but you have not set CSRF_COOKIE_SECURE to True. Using a secure-only CSRF cookie makes it more difficult for network traffic sniffers to steal the CSRF token.
?: (security.W017) You have 'django.middleware.csrf.CsrfViewMiddleware' in your MIDDLEWARE_CLASSES, but you have not set CSRF_COOKIE_HTTPONLY to True. Using an HttpOnly CSRF cookie makes it more difficult for cross-site scripting attacks to steal the CSRF token.
?: (security.W018) You should not have DEBUG set to True in deployment.
?: (security.W019) You have 'django.middleware.clickjacking.XFrameOptionsMiddleware' in your MIDDLEWARE_CLASSES, but X_FRAME_OPTIONS is not set to 'DENY'. The default is 'SAMEORIGIN', but unless there is a good reason for your site to serve other parts of itself in a frame, you should change it to 'DENY'.
System check identified 6 issues (0 silenced).
if you get errors like this add this in settings.py as show below
settings.py
CSRF_COOKIE_SECURE= True
X_FRAME_OPTIONS='DENY'
SESSION_COOKIE_SECURE=True
SECURE_BROWSER_XSS_FILTER=True
SECURE_CONTENT_TYPE_NOSNIFF=True
Django getting url avoiding hard coding
Feb. 15, 2020, 12:29 p.m.
328Django Getting Url Avoiding Hard Coding
Assume that we have an url design like this:
url('^posts/(?P<slug>[-\w]+)/$',view_post,name="posts"),
and we are using getabsoluteurl() function.Instead of coding such as:
return "/posts/%s" %self.slug
we can use reverse() from django.core.urlresolvers:
return(reverse('posts', args=[self.slug, ]))
it will get automatically url we need
Get user ip, even if they're behind proxies in django
Feb. 15, 2020, 12:26 p.m.
184Get user IP, even if they're behind proxies in django
This is from my improvement of an answer on stackoverflow about user's IP address, taking proxies into account.
If the user is behind a proxy, the HTTPXFORWARDED_FOR header contains a comma seperated list of IP's. The first IP is the clien'ts internal IP address, followed by one or more proxies or load balancers that may have handled the request. Read more about the header on Wikipedia.
This solution focuses on getting the external IP address of the last client (the proxy address), which is the right-most address in the header.
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[-1].strip()
else:
ip = request.META.get('REMOTE_ADDR')
return ip
How to dump data and load data in django
Feb. 15, 2020, 11:48 a.m.
194How to dump data and load data in django
dumpdata command:
It is a django management command, which can be use to backup(export) you model instances or whole database
database dump:
Following command will dump whole database in to a db.json
file
python manage.py dumpdata > db.json
backup specific app:
Following command will dump the content in django admin
app into admin.json
file
python manage.py dumpdata admin > admin.json
dumpdata (--exclude)
-
You can use
--exclude
option to specify apps/tables which don't need being dumped -
Following command will dump the whole database with out including
auth.permission
table content
python manage.py dumpdata --exclude auth.permission > db.json
dumpdata (--indent)
-
By default,
dumpdata
will output all data on a single line. It isn’t easy for humans to read -
You can use the
--indent
option to pretty-print the output with a number of indentation spaces
python manage.py dumpdata auth.user --indent 2 > user.json
dumpdata (--format)
-
By default, dumpdata will format its output in JSON
-
You can specify the format using --format option
-
Command supports for following formats(serialization formats)
- json
- xml
- yaml
python manage.py dumpdata auth.user --indent 2 --format xml > user.xml
loaddata command
This command can be use to load the fixtures(database dumps) into database
python manage.py loaddata user.json
above command will add the user.json
file content into the database
Restore fresh database
-
When you backup whole database by using
dumpdata
command, it will backup all the database tables -
If you use this database dump to load the fresh database(in another django project), it can be causes
IntegrityError
(If youloaddata
in same database it works fine) -
To fix this problem, make sure to backup the database by excluding
contenttypes
andauth.permissions
tables
python manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json
- Now you can use
loaddata
command with a fresh database
python manage.py loaddata db.json
Manage login and logout history with django admin
Feb. 15, 2020, 10:50 a.m.
220Manage login and logout history with Django admin
The admin admin site and User model that come with Django by default are very useful.
This time, we will create an application that manages the login / logout history of this User model. It may be used for a small workbook.
models.py
from django.conf import settings
from django.contrib.auth.signals import user_logged_in, user_logged_out
from django.db import models
from django.dispatch import receiver
from django.utils import timezone
class AttendanceRecord(models.Model):
"" "Attendance Book" ""
user = models.ForeignKey(
settings.AUTH_USER_MODEL, verbose_name='user', on_delete=models.PROTECT,)
login_time = models.DateTimeField('Login time', blank=True, null=True)
logout_time = models.DateTimeField('Logout time', blank=True, null=True)
def __str__(self):
login_dt = timezone.localtime(self.login_time)
return '{0} - {1.year}/{1.month}/{1.day} {1.hour}:{1.minute}:{1.second} - {2}'.format(
self.user.username, login_dt, self.get_diff_time()
)
def get_diff_time(self):
"" "Logout time-Login time" ""
if not self.logout_time:
return 'Not logged out'
else:
td = self.logout_time - self.login_time
return '{0}Time {1} minutes'.format(
td.seconds // 3600, (td.seconds // 60) % 60)
@receiver(user_logged_in)
def user_logged_in_callback(sender, request, user, **kwargs):
"" "Called when logging in" ""
AttendanceRecord.objects.create(user=user, login_time=timezone.now())
@receiver(user_logged_out)
def user_logged_out_callback(sender, request, user, **kwargs):
"" "Called when you log out" ""
records = AttendanceRecord.objects.filter(user=user, logout_time__isnull=True)
if records:
record = records.latest('pk')
record.logout_time = timezone.now()
record.save()
admin.py
from django.contrib import admin
from .models import AttendanceRecord
from django.db import models
@admin.register(AttendanceRecord)
class Attendancerecord(admin.ModelAdmin):
list_display = ['user_id', 'login_time', 'logout_time']
How to restrict access to parts of django admin
Feb. 15, 2020, 10:04 a.m.
127How to restrict access to parts of Django admin
You can enable and restrict access to specific parts of Django admin using the permission system. When a model is added, by default, Django creates three permissions. add, change and delete
You can add more complex logic to restrict access by changing these methods:
def has_add_permission(self, request):
...
def has_change_permission(self, request, obj=None):
...
def has_delete_permission(self, request, obj=None):
...
def has_module_permission(self, request):
...
Website maintenance mode in django
Feb. 13, 2020, 12:10 p.m.
225website maintenance mode in django
In a large-scale update of a website, you may want to temporarily hide the web page, use it as a link to elucidate the cause when a sudden problem occurs, or use it for small websites later. Yes, but useful if you are editing the source directly on the server.
The announcements will make it easier for users to understand. Also, since it returns with an HTTP status code of 503, it also considers SEO convenience.
RUN:
pip install django-maintenance-mode
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'maintenance_mode', # add this
'app.apps.AppConfig', # Your own Django app
]
Let's create By default, 503.html directly under templates is read.
templates/503.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>kwikl3arn</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css">
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
</head>
<body>
<section class="section">
<div class="container">
<h1 class="title">Site maintenance in progress ...</h1>
<span class="icon has-text-info is-large">
<i class="fas fa-wrench fa-3x fa-spin"></i>
</span>
</div>
</section>
</body>
</html>
Start and end of maintenance mode
There are several ways to enter and exit maintenance mode. as shown below, use one for maintenance mode
1)Switch by accessing the URL (for super users only)
Accessing a URL turns on maintenance mode. The URL for django-maintenance-mode
that is provided on the side.
urls.py
path('maintenance-mode/', include('maintenance_mode.urls')),
2)Switch by command
You can also switch to maintenance mode with the following command:
python manage.py maintenance on
python manage.py maintenance off
3)Using functions
set_maintenance_mode()Function is provided, and you can switch with it.
from maintenance_mode.core import set_maintenance_mode
set_maintenance_mode(True)
set_maintenance_mode(False)
#The get_maintenance_mode()function can also determine if it is currently under maintenance.
from maintenance_mode.core import get_maintenance_mode
# During maintenance
if get_maintenance_mode():
...
4)Some users can see during maintenance
Some users will also want the ability to access regular pages while in maintenance mode.
First, settings.py
let's write the following. Even during maintenance, the admin management site can be used, and operations such as login can be performed.
# The management site can be used even during maintenance.
MAINTENANCE_MODE_IGNORE_ADMIN_SITE = True
In addition, if you want logged-in users to be able to view regular pages, specify the following:
# Login users can view normal pages during maintenance.
MAINTENANCE_MODE_IGNORE_AUTHENTICATED_USER = True
If you want to apply only to is_staff
authorized or is_superuser
authorized users, not login users, you have the following settings:
# is_staff users can see the normal page during maintenance.
MAINTENANCE_MODE_IGNORE_STAFF = True
# is_superuser user can see the normal page even during maintenance.
MAINTENANCE_MODE_IGNORE_SUPERUSER = True
5)Make switching easy
It is easy for super users to turn on / off maintenance mode with one click. Let's prepare a link in the navigation bar etc. and switch it with one click.
settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(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',
'maintenance_mode.context_processors.maintenance_mode', # add this
],
},
},
]
Make the following settings so that you can log in even during maintenance and that super users can access normal pages.
MAINTENANCE_MODE_IGNORE_ADMIN_SITE = True
MAINTENANCE_MODE_IGNORE_SUPERUSER = True
After that, let's write the following in the template.
{% if user.is_superuser %}
{% if maintenance_mode %}
<a href="{% url 'maintenance_mode_off' %}">End of maintenance</a>
{% else %}
<a href="{% url 'maintenance_mode_on' %}">Start maintenance</a>
{% endif %}
{% endif %}
Do the same for users with staff rights etc.
If you want to do the same in the user of staff privileges, create a view that calls the on / off switching function that was introduced in the "use of the function" on their own, the template {% if user.is_superuser %}
and {% url 'maintenance_mode...' %}
change the part to staff rights and your own view, MAINTENANCE_MODE_IGNORE_STAFF=True
It is OK if the staff can access the self-made view even during maintenance.
Or, MAINTENANCE_MODE_IGNORE_URLS
you can set it so that you can access the self-made URL for switching even during maintenance.
for more details https://github.com/fabiocaccamo/django-maintenance-mode
Creating custom template filter that injects adsense ad code after n paragraph in django
Jan. 22, 2020, 7:01 p.m.
265Creating Custom Template Filter That Injects Adsense Ad Code After N Paragraph in Django
Injecting ads inside content is a very effective technique. Let's say you want to inject Adsense ad after the first paragraph of text. To add such capability to our Django-based website we need to create a custom filter for that. I'll tell you how to implement such a filter.
1) In your app, create a templatetags/adsense_tags.py file with the following code:
from django import template
from django.template.loader import render_to_string
register = template.Library()
@register.filter
def inject_adsense_after_paragraph(value, arg):
# Render our adsense code placed in html file
ad_code = render_to_string("adsense_ads.html")
# Break down content into paragraphs
paragraphs = value.split('</p>')
# Check if paragraph we want to post after exists
if arg < len(paragraphs):
# Append our code before the following paragraph
paragraphs[arg] = ad_code + paragraphs[arg]
# Assemble our text back with injected adsense code
value = '</p>'.join(paragraphs)
return value
2) Then you need to put your Adsense code into the templates/adsense_ads.html file, you may have something like this:
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-xxxxxxxxxxx"
data-ad-slot="xxxxxxxxxxx"
data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
3) In the end, let's use our filter on content, let's say your blog post has a following template blog/blogpost_detail.html:
{% extends 'base.html' %}
{% load adsense_tags %}
{% block content %}
{% blog.title %}
{% blog.body|inject_adsense_after_paragraph:1|safe %}
{% endblock content %}
As you see, all we need to do is to add filter inject_adsense_after_paragraph to our blog body and pass number of the paragraph after which we want to show the ad. In our case, we want to display the add after the first paragraph of text.
How to install django debug toolbar
Jan. 22, 2020, 2:55 p.m.
335How To Install Django Debug Toolbar
First install
pip install django-debug-toolbar
settings.py:
Next, include it to project's installed apps, but be careful - it's always a good practice to use a different settings.py
file for such development-only apps and middlewares as debug toolbar:
Debug toolbar also relies on static files, so appropriate app should be included as well:
# If environment is dev...
DEBUG = True
INSTALLED_APPS = [
# ...
'django.contrib.staticfiles',
'debug_toolbar',
# ...
]
STATIC_URL = '/static/'
MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware']
def show_toolbar(request):
return True
DEBUG_TOOLBAR_CONFIG = {
"SHOW_TOOLBAR_CALLBACK" : show_toolbar,
}
In some cases, it's also required to set INTERNAL_IPS
in settings.py
:
INTERNAL_IPS = ('127.0.0.1', )
urls.py:
In urls.py
, as official documentation suggests, the next snippet should enable debug toolbar routing:
if settings.DEBUG and 'debug_toolbar' in settings.INSTALLED_APPS:
import debug_toolbar
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
]
Collect toolbar's static after installation:
python manage.py collectstatic
That's it, debug toolbar will appear on you project's pages, providing various useful information about execution time, SQL, static files, signals, etc.
Aggregation usage in django queries
Jan. 21, 2020, 10:22 p.m.
1223Aggregation usage in django queries
The meaning of aggregation is "the collection of related items of content so that they can be displayed or linked to".
Cases when Aggregation is used:
-
To find "maximum", "minimum" value of column(field in django) in database table in django terms a model.
- To find "count" of records in database table based on a column/field value.
- To find "average" value of a group of similar objects
- To find "sum" of values of a column of a table/model in database.
- In most of the cases we use aggregation on columns of data type "integer", "float", "date", "datetime" etc.
Consider below django model to learn queries that use aggregation
class Book(models.Model):
name = models.CharField(max_length=300)
pages = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
rating = models.FloatField()
Usage of "Avg" in django queryset
Find average price across all books?
from django.db.models import Avg
out = Book.objects.aggregate(Avg('price'))
# value of out is something like {'price__avg': 34.35}
Find average price across all books which contains "django" in name?
from django.db.models import Avg
queryset = Book.objects.filter(name__icontains='django')
out = queryset.aggregate(Avg('price'))
# value of out is something like {'price__avg': 54.25}
Find average price across all books which has minimum price of 14?
from django.db.models import Avg
queryset = Book.objects.filter(price__gte=14)
out = queryset.aggregate(Avg('price'))
# value of out is something like {'price__avg': 25.65}
Usage of "Max" in django queryset
Find maximum price across all books?
from django.db.models import Max
out = Book.objects.aggregate(Max('price'))
# value of out is something like {'price__max': 81.20}
Find maximum price across all books which contains "django" in name?
from django.db.models import Max
queryset = Book.objects.filter(name__icontains='django')
out = queryset.aggregate(Max('price'))
# value of out is something like {'price__max': 54.25}
Usage of "Min" in django queryset
Find minimum price across all books?
from django.db.models import Min
out = Book.objects.aggregate(Min('price'))
# value of out is something like {'price__min': 81.20}
Find minimum price across all books which contains "django" in name?
from django.db.models import Min
queryset = Book.objects.filter(name__icontains='django')
out = queryset.aggregate(Min('price'))
# value of out is something like {'price__min': 54.25}
Usage of "SUM" in django queryset
Find sum of prices all books?
from django.db.models import Sum
out = Book.objects.aggregate(Sum('price'))
# value of out is something like {'price__sum': 81.20}
find sum of all prices of books which contains "django" in name
from django.db.models import Min
queryset = Book.objects.filter(name__icontains='django')
out = queryset.aggregate(Sum('price'))
# value of out is something like {'price__sum': 54.25}
Usage of "COUNT" in django queryset
Find count of all books?
from django.db.models import Count
out = Book.objects.aggregate(Count('rating'))
# value of out is something like {'rating__count': 8}
find count of all prices of books which contains "django" in name
from django.db.models import Count
queryset = Book.objects.filter(name__icontains='django')
out = queryset.aggregate(Sum('price'))
# value of out is something like {'rating__count': 5}
Multiple aggregations in a single query
from django.db.models import Avg, Max, Min
Book.objects.aggregate(Avg('price'), Max('price'), Min('price'))
# value of out is something like
# { 'price__avg': 34.35, 'price__max': 81.20, 'price__min': 12.99}
These are the very basic queries that used aggregation. we can also use aggregation on "foreign key" fields, "many-to-many" fields and we can also use it with joins("__" notation in django).
Django project layout and settings
Jan. 21, 2020, 9:55 p.m.
204Django project layout and settings
Let's talk about "Django" project structure in depth. You can see the complete project layout in above image.
base/project/: It is a container for our project. we can give any name to this directory and we can modify it at any time.
project/manage.py: It is created for all django projects. It is a command-line utility, it is used to interact with the "django" project in many ways.
We use below command to run development server
python manage.py runserver
"runserver" is a command which is used to run the server.
To show all available commands run the below command
python manage.py
project/project: This directory contains the project files.
project/project/__init__.py: It is a empty file that tells python to consider the directory as a package.
project/project/settings.py: It contains all configuration settings like database settings, installed apps, root url conf etc.
project/project/urls.py: It is the root url file. It contains url patterns to map the request to the respective view to process it.
project/project/uwsgi.py: An entry-point for WSGI-compatible web servers to serve our project.
project/static: It contains the static assets like css, javascript, images, etc.
project/templates: It contains the html files that will be used to create http response to a request.
project/media: It is a path to store the media contents like files that are uploaded by users.
To get project structure that is shown in above image. we need to update settings.py file with below code.
-
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR + '/media/') MEDIA_URL = '/media/' STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"), ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["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', ], }, }, ]
- To know more about customizing settings visit: https://docs.djangoproject.com/en/2.2/ref/settings/
- project/app1: It is a python package, It contains application related files.
- project/app1/templatetags: It's a directory that contains template tags of our application. Template tags helps us at the time of rendering the template. It takes the context from the template and processes it and again return it to the template.
- project/app1/templatetags/__init__.py: It's empty python file, it tells python to recognize the directory as a python package.
- project/app1/templatetags/tags.py: It's a python file, it contains the custom template tags that we will use it in templates.
- project/app1/apps.py: It contains the application's configuration.
- project/app1/models.py: It contains the models(db tables) of application. we represent our database tables with the model in django. ORM(Object Relation Mapper) converts the models to db tables. We do not use raw SQL(Structured Query Language) to query the database, instead we use django queries. ORM convert these queries into SQL equivalent code and performs the db query and again converts the relational data to python objects to make things easier.
- project/app1/migrations: It contains the database migrations of application, each migration contains the database schema related code.
- project/app1/migrations/__init__.py: It's empty python file, it tells python to recognize the directory as a python package.
- project/app1/migrations/001_initial.py: It's a migration file of application. It contains the database schema related code, that is used to create database schema.
- project/app1/__init__.py: It's a python file, it tells python to recognize the directory as a python package.
- project/app1/admin.py: Django provides the inbuilt admin panel. This file contains the admin related code.
- project/app1/urls.py: It contains url's that are related to the application.
- project/app1/views.py: It contains the views(functions/classes) that are mapped from the url's to process the request.
- project/app1/tests.py: It contains the unit tests of the application.
Gitignore for django
Jan. 17, 2020, 2:21 p.m.
302gitignore for django
If you are using Git for version control, you need a Gitignore file to ignore all files that don’t matter and shouldn’t be in your git repository. Think of your virtual environment and all the .pyc files. Those are both generated and can be generated by anyone that has access to your code. Therefore, it’s unnecessary to add those to your repository.
There are a lot of different file types and specific folders that you don’t need. Even outside of Django. Think about your personal settings in VS Code (if you use that). Here is a list which covers all things that you can ignore through gitignore for every Django project you start. Put this list in the root of your Django project and call it .gitignore
(yes, with the dot!).
# Django #
*.log
*.pot
*.pyc
__pycache__
db.sqlite3
media
# Backup files #
*.bak
# If you are using PyCharm #
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.xml
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/gradle.xml
.idea/**/libraries
*.iws /out/
# Python #
*.py[cod]
*$py.class
# Distribution / packaging
.Python build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
.pytest_cache/
nosetests.xml
coverage.xml
*.cover
.hypothesis/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery
celerybeat-schedule.*
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# mkdocs documentation
/site
# mypy
.mypy_cache/
# Sublime Text #
*.tmlanguage.cache
*.tmPreferences.cache
*.stTheme.cache
*.sublime-workspace
*.sublime-project
# sftp configuration file
sftp-config.json
# Package control specific files Package
Control.last-run
Control.ca-list
Control.ca-bundle
Control.system-ca-bundle
GitHub.sublime-settings
# Visual Studio Code #
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history
How to enable or disable csrf validation in django
Jan. 11, 2020, 5:40 a.m.
693How To Enable Or Disable CSRF Validation In Django
Django has provide a feature that can help you to avoid csrf attack on your Django application. But some times especially in your development environment, you do not want this feature when send post request to your web server use curl in command line, if this feature enabled, you will get errors. This article will tell you how to enable or disable csrf validation in Django application.
1. Enable CSRF.
The csrf function is enabled by default in Django app. So if you do not disable it before, it is enabled by default. If you want to pass the csrf validation in your django code, you can add below code in your template html page form web element.
<form method="post" action="{% url 'register' %}">
......
<!-- avoid CSRF verification failed error. -->
{% csrf_token %}
......
</form>
If you use curl to send a POST request to your Django web app when csrf validation is enabled, you will get bellow error.
:~$ curl -i -X POST http://127.0.0.1:8000/kwikl3arn/register
HTTP/1.1 403 Forbidden
Date: Wed, 11 Jan 2020 05:40:21 GMT
Server: WSGIServer/0.2 CPython/3.6.7
Content-Type: text/html
X-Frame-Options: SAMEORIGIN
Content-Length: 2868
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="robots" content="NONE,NOARCHIVE">
......
</html>
2. Disable CSRF Validation
2.1 Disable CSRF Validation For Entire Django Project
a)Edit django project settings.py file
b)Comment or remove ‘django.middleware.csrf.CsrfViewMiddleware’ in MIDDLEWARE list then csrf validation has been removed from this django app. All post request in this django project without csrf tag will not meet error.
settings.py
MIDDLEWARE = [
......
#'django.middleware.csrf.CsrfViewMiddleware',
......
]
2.2 Disable CSRF Validation For Class Based View.
You can also disable csrf validation for single class based view use method_decorator and csrf_exempt.
views.py
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
@method_decorator(csrf_exempt, name='dispatch')
class TestClassBasedView(View):
def get(self, request):
......
2.3 Disable CSRF Validation For Function Based View.
Below code will disable csrf validation for single function based view use csrf_exempt.
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def test_function_based_view(request):
if(request.method=='GET'):
......
Show single instance of duplicate instances in django admin
Jan. 11, 2020, 2:08 a.m.
596model.py
from django.db import models
class TestModel(models.Model):
title = models.TextField(max_length=150)
slug = models.TextField(max_length=150)
modified = models.DateTimeField(auto_now=True)
Then you can do this in the ModelAdmin's queryset
method
admin.py
method1:
from django.contrib import admin
import models
class TestModelAdmin(admin.ModelAdmin):
list_display = ('title', 'slug', 'modified')
def queryset(self, request):
qs = super(TestModelAdmin, self).queryset(request)
qs = qs.order_by('slug', '-modified').distinct('slug')
return qs
admin.site.register(models.TestModel, TestModelAdmin)
method 2:
from django.contrib import admin
import models
class TestModelAdmin(admin.ModelAdmin):
list_display = ('title', 'slug', 'modified')
def queryset(self, request):
qs = super(TestModelAdmin, self).queryset(request)
qs = qs.extra(where=[
"id IN (SELECT id FROM(SELECT * FROM myapp_testmodel ORDER BY modified DESC)AS last_modified GROUP BY slug)"
])
return qs
admin.site.register(models.TestModel, TestModelAdmin)
How to restrict access to parts of django admin
Jan. 4, 2020, 12:58 a.m.
127How to restrict access to parts of Django admin
You can enable and restrict access to specific parts of Django admin using the permission system. When a model is added, by default, Django creates three permissions. add, change and delete
Admin uses these permissions to decide access for users. For a user with is_superuser=False
, and no permissions
If you add a permission user.user_permissions.add(Permission.objects.get(codename="add_hero")).
You can add more complex logic to restrict access by changing these methods:
admin.py
def has_add_permission(self, request):
...
def has_change_permission(self, request, obj=None):
...
def has_delete_permission(self, request, obj=None):
...
def has_module_permission(self, request):
...
How to set the plural text for a model
Jan. 4, 2020, 12:47 a.m.
192How to set the plural text for a model
By default admin will show the name of your model appended with an “s”, aka the plural form of your model
You have been asked to set the correct plural spellings: Categories and Heroes
You can do this by setting the verbose_name_plural
in your models. Change that in your models.py.:
class Category(models.Model):
...
class Meta:
verbose_name_plural = "Categories"
class Hero(Entity):
...
class Meta:
verbose_name_plural = "Heroes"
now check u r admin page
How to mark a field as read only in django admin
Jan. 4, 2020, 12:41 a.m.
441How to mark a field as readonly in admin
kwikl3arn has temporarily decided to stop tracking the family trees of mythological entities. You have been asked to make the father
, mother
and spouse
fields readonly.
You can do this by:
admin.py
@admin.register(Hero)
class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):
...
readonly_fields = ["father", "mother", "spouse"]
How to add date based filtering in django admin
Jan. 4, 2020, 12:37 a.m.
295How to add date based filtering in Django admin
You can add a date based filtering on any date field by setting the date_hierarchy
.
admin.py
@admin.register(Hero)
class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):
...
date_hierarchy = 'added_on'
How to disable django admin pagination
Jan. 4, 2020, 12:35 a.m.
480How to disable django admin pagination
If you want to completely disable pagination on a admin listview page, you can do this.
admin.py
import sys
...
@admin.register(Hero)
class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):
...
list_per_page = sys.maxsize
How to add pagination in django admin
Jan. 4, 2020, 12:29 a.m.
1169How to add pagination in django admin
You have been asked to increase the number of heroes one can see on a single page to 250. (The default is 100). You can do this by:
admin.py
@admin.register(Hero)
class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):
...
list_per_page = 250 # add this as per u wan to see the length of pagination
How to remove default apps from django admin
Jan. 3, 2020, 11:39 p.m.
1051How to remove default apps from Django admin
Django will include django.contrib.auth
in INSTALLED_APPS
, which means User and Groups models are included in admin automatically.
If you want to remove it, you will have to unregister them.
from django.contrib.auth.models import User, Group
admin.site.unregister(User)
admin.site.unregister(Group)
we are done.
How to change ‘django administration’ text
Jan. 3, 2020, 10:19 p.m.
263How to change ‘Django administration’ text
By default Django admin shows ‘Django administration’. You have been asked to replace this with ‘kwikl3arn Administration’
The text is at these pages:
- Login Page
- The listview page
- The HTML title tag
add following lines to urls.py
from django.contrib import admin
# Admin Site Config
admin.sites.AdminSite.site_header = 'My site admin header'
admin.sites.AdminSite.site_title = 'My site admin title'
admin.sites.AdminSite.index_title = 'My site admin index'
Why use a custom manager in django
Jan. 2, 2020, 1:52 p.m.
192Why use a Custom Manager in django
Let’s assume you have a model that looks like the following:
class Person(models.Model):
email = models.EmailField(max_length=250)
first_name = models.CharField(max_length=45)
last_name = models.CharField(max_length=45)
You might be tempted to write a function that gets a Person by “email”, then you might write a similar function to retrieve a Person by “last_name”
Something like:
def get_person_by_email(email):
return Person.objects.get(email=email)
def get_person_by_last_name(last_name):
return Person.objects.get(last_name=last_name)
Then, over time, you decide that it would be awesome if you could get all the people in your system with similar domain names in their emails. I want a count of all the people who signed up for my services that have “gmail” email addresses. You could do
something like this:
def count_people_by_email_domain(domain):
return len(Person.objects.filter(email__endswith="domain"))
You could see that you might have an infinite number of small functions that can manipulate the data anyway that you see fit.
Why not put those functions inside a custom Manager class instead?
That way, instead of writing a bunch of tiny functions and having to import them everywhere you need them, all you have to do is import the model and run the function on the model’s custom Manager class instead!
from models import Person
# using a custom Manager on email...
people = Person.emails.filter_domain(domain)
person = Person.emails.get(email)
# using a custom Manager on last_name...
person = Person.last_names.get(last_name)
# etc...
How to Implement a custom manager…
Have I sold you on Custom Managers yet? The great news is that you can break your models up into a bunch of small, specific Manager classes and use them on your models.
Here is a simple Manager class that you can try out right now on our Person Model.
from django.db import models
# maybe through your Manager classes into "managers.py"
class EmailManager(models.Manager):
def filter_domain(self, domain):
return super(EmailManager, self).get_queryset().filter(email__endswith=domain)
def get(self, email):
return super(EmailManager, self).get_queryset().get(email=email)
# models.py
class Person(models.Model):
# our model data...
emails = EmailManager()
That’s how you create a manager that encapsulates most of the tiny functions laying around your model. Just throw them into a customer Manager, and you’ll be much happier and so will your models!
Test your queries before they make it into production using the django shell
Jan. 2, 2020, 1:44 p.m.
308Test your Queries before they make it into Production using the Django Shell
You have a database, you have a Django project and a couple third party Django apps that you installed. You create your models, and now you want to try to test a few queries to see if your models are actually going to work.
Where do I start? How can I test to see if my models are going to work? I wish I could access my database to run some SQL queries with Django to see them in action!
Don’t ever write queries in your Django apps before you are sure they are going to do what you want them to do.
What I tend to do, is I open up my Python interpreter. Oh, not just any Python interpreter, but the one that comes with Django.
$ ./manage.py shell
At this point, you can run some Django queries to see what kind of data you will get. This will allow you see what happens when you perform some queries with a lot faster turn over rate. No need to worry about having to create a fake view, fake template, fake url, etc in order to see what query you need to use.
Let’s see an example.
Suppose we have a model called ‘Animal’ and 2 models ‘Cat’ and ‘Dog’ for some Polymorphism Django ORM magic (maybe you have a animal rescue website, so you need to query both Cats and Dogs in the same ‘Animal’ query
class Animal(models.Model):
name = models.CharField(max_length=40)
created_data = models.DateTimeField(auto_now_add=True)
class Dog(Animal):
house_broken = models.BooleanField(default=False)
class Cat(Animal):
litter_trained = models.BooleanField(default=False)
Open up your shell using the command above.
Now, you need to import the models:
import pets.models import Animal, Dog, Cat
Now, simply run some queries to see what kind of data you retrieve.
dog1 = Dog.objects.create(name="Bullseye", house_broken=True)
dog2 = Dog.objects.create(name="SpogeBob")
cat1 = Cat.objects.create(name="Tom", litter_trained=True)
cat2 = Cat.objects.create(name="SnowBell")
dog1.save()
dog2.save()
cat1.save()
cat2.save()
animals1 = Animal.objects.all()
animals2 = Animal.objects.filter(created_data__year=2019)
You can do anything you want in the shell. It may take a little longer because you have to write everything out. The great part of this is, you don’t have to create anything other than the models. I created the models in seconds and I wanted to see what these queries would actually do.
What is secret_key in django
Jan. 2, 2020, 1:37 p.m.
240What Is SECRET_KEY in Django?
Do you ever want to know how the SECRET_KEY works? It’s sitting in your settings.py file but do you ever wonder why you need it? If you look at the documentation, you’ll discover some very interesting things about the SECRET_KEY setting.
In the Cryptographic signing section of the Django docs, it says:
You may also find signing useful for the following:
- Generating “recover my account” URLs for sending to users who have lost their password.
- Ensuring data stored in hidden form fields has not been tampered with.
- Generating one-time secret URLs for allowing temporary access to a protected resource, for example a downloadable file that a user has paid for.
And I’m going to add one more thing to this list: Signing cookies so that you know that your users’ cookies are not being tampered by a hacker.
How can you use the SECRET_KEY to determine if data has been tampered?
The first thing you need to do is sign your data.
from django.core.signing import Signer
signer = Signer()
value = signer.sign("My secret data")
value
Now, your signed data is saved in the value
variable. How do you make sure that your data hasn’t been tampered with?
from django.core import signing
value += 'd'
try:
original = signer.unsign(value)
except signing.BadSignature:
print ("Tampering detected!")
If the value is different, the unsign
function will throw a BadSignature
exception. The Signer
class uses the setting.SECRET_KEY
to create the hash of the signed data.
Next time you have data that you need to keep from being tampered remember the Signer
class.
Designing custom 404 and 500 error pages in django
Dec. 31, 2019, 7:30 a.m.
355Designing custom 404 and 500 error pages in Django
views.py
from django.shortcuts import render
from django.http import HttpResponse
def error_404_view(request, exception):
data = {"name": "kwikl3arn.com"}
return render(request, '404.html', data)
def error_500_view(request):
data = {"name": "kwikl3arn.com"}
return render(request, '500.html', data)
urls.py
from myapp import views as myapp_views
from django.conf.urls import handler404, handler500
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^myapp/', include('myapp.urls', namespace='myapp')),
]
handler404 = myapp_views.error_404_view
handler500 = myapp_views.error_500_view
myapp/templates/404.html
404.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
404 error my
{{name}}
</body>
</html>
myapp/templates/500.html
500.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
my 500 error
{{name}}
</body>
</html>
Indexing your django models
Dec. 31, 2019, 5:37 a.m.
206Indexing your Django models
If you have come to Django with a fairly good MySQL, PostgreSQL background this will be obvious. If your experience of databases is creating a Django model, this may be of use to you.
Here is an example model
class Blog(models.Model):
title = models.CharField(max_length=100)
added = models.DateTimeField(auto_now_add=True)
body = models.TextField()
You might be thinking whats wrong....
Well now lets assume you have 2000 entries in your database and you decied you want to list your items in order they were added, or by title. Databases are great, but without indexes it needs to scan over 2000 rows to figure out the order.
Heres the better version of the same model
class Blog(models.Model):
title = models.CharField(db_index=True, max_length=100)
added = models.DateTimeField(db_index=True, auto_now_add=True)
body = models.TextField()
So, whats better?
Well, now there are indexes, your database server just needs to take a look over the list of indexes. Its a lot faster.
When to use indexes
A good rule, if you are going to order by, or filter by, it should be indexed.
Track the number of “page views” or “hits” of an object in django
Dec. 20, 2019, 5:05 p.m.
252Track the number of “page views” or “hits” of an object in django
models.py
from django.db import models
class UrlHit(models.Model):
url = models.URLField()
hits = models.PositiveIntegerField(default=0)
def __str__(self):
return str(self.url)
def increase(self):
self.hits += 1
self.save()
class HitCount(models.Model):
url_hit = models.ForeignKey(UrlHit, editable=False, on_delete=models.CASCADE)
ip = models.CharField(max_length=40)
session = models.CharField(max_length=40)
date = models.DateTimeField(auto_now=True)
views.py
from django.shortcuts import render
from .models import UrlHit, HitCount
def homepage(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
# Let's assume that the visitor uses an iPhone...
if not request.session.session_key:
request.session.save()
s_key = request.session.session_key
url, url_created = UrlHit.objects.get_or_create(url=request.path)
if url_created:
track, created = HitCount.objects.get_or_create(url_hit=url, ip=ip, session=s_key)
if created:
url.increase()
request.session[ip] = ip
request.session[request.path] = request.path
else:
if ip and request.path not in request.session:
track, created = HitCount.objects.get_or_create(url_hit=url, ip=ip, session=s_key)
if created:
url.increase()
request.session[ip] = ip
request.session[request.path] = request.path
print(url.hits)
resp = render(request=request,
template_name='home.html'
)
return resp
urls.py
from django.urls import path
from kwikl3arnapp import views
urlpatterns = [
path('', views.homepage, name='home')
]
home.html
<!DOCTYPE html>
<html>
<head>
<title>kwikl3arn.com</title>
</head>
<body>
<h1>home page</h1>
</body>
</html>
Multiple model django search engine
Dec. 19, 2019, 5:01 p.m.
196Multiple Model Django Search Engine
models.py
from django.db import models
from django.db.models import Q
class PostQuerySet(models.QuerySet):
def search(self, query=None):
qs = self
if query is not None:
or_lookup = (Q(tutorial_title__icontains=query) |
Q(description__icontains=query)|
Q(tutorial_slug__icontains=query)
)
qs = qs.filter(or_lookup).distinct() # distinct() is often necessary with Q lookups
return qs
class PostManager(models.Manager):
def get_queryset(self):
return PostQuerySet(self.model, using=self._db)
def search(self, query=None):
return self.get_queryset().search(query=query)
class Lesson(models.Model):
title = models.CharField(max_length=120)
description = models.TextField(null=True, blank=True)
slug = models.SlugField(blank=True, unique=True)
featured = models.BooleanField(default=False)
publish_date = models.DateTimeField(auto_now_add=False, auto_now=False, null=True, blank=True)
class Tutorial(models.Model):
tut_title = models.CharField(max_length=200)
tut_published = models.DateTimeField(default=datetime.now, blank=True)
tut_slug = models.CharField(max_length=200, default=1)
objects = PostManager()
def __str__(self):
return self.tutorial_title
views.py
from itertools import chain
from django.views.generic import ListView
from .models import Tutorial, Lesson
class SearchView(ListView):
template_name = 'search/view.html'
paginate_by = 20
count = 0
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['count'] = self.count or 0
context['query'] = self.request.GET.get('q')
return context
def get_queryset(self):
request = self.request
query = request.GET.get('q', None)
if query is not None:
blog_results = Tutorial.objects.search(query)
lesson_results = Lesson.objects.search(query)
# combine querysets
queryset_chain = chain(
blog_results,
lesson_results,
)
qs = sorted(queryset_chain,
key=lambda instance: instance.pk,
reverse=True)
self.count = len(qs) # since qs is actually a list
return qs
return Tutorial.objects.none() # just an empty queryset as default
1)create new folder as templatetags inside your app
2)after createing templatetags folder creae new file inside and name it as __init__.py leve it as blank
3)after createing __init__.py file ,create another file inside templatetags and name it as class_name.py write the below code inside class_name.py
class_name.py
from django import template
register = template.Library()
@register.filter()
def class_name(value):
return value.__class__.__name__
if u created above two your folder look like this
myapp/templatetags/
- __init__.py
- class_name.py
1)create new folder as templates inside your app
2)after createing templatetags folder create another folder inside and name it as search
3)after createing search folder, create another file inside search folder and name it as view.html
view.html
{% load class_name %}
<div class='row title-row my-5'>
<div class='col-12 py-0'>
<h3 class='my-0 py-0'>{{ count }} results for <b>{{ query }}</b></h3>
</div>
</div>
<div class='row'>
<div class='col-12 col-md-6 mx-auto my-5 py-5'>
<form method='GET' class='' action='.'>
<div class="input-group form-group-no-border mx-auto" style="margin-bottom: 0px; font-size: 32px;">
<span class="input-group-addon cfe-nav" style='color:#000'>
<i class="fa fa-search" aria-hidden="true"></i>
</span>
<input type="text" name="q" data-toggle="popover" data-placement="bottom" data-content="Press enter to search" class="form-control cfe-nav mt-0 py-3" placeholder="Search..." value="" style="" data-original-title="" title="" autofocus="autofocus">
</div>
</form>
</div>
</div>
{% for object in object_list %}
{% with object|class_name as klass %}
{{ query }}
{% if klass == 'Post' %}
<div class='row'>
<div class='col-12'>
Blog post: <a href='{{ object.get_absolute_url }}'>{{ object.title }}</a>
</div>
</div>
{% elif klass == 'Lesson' %}
<div class='row'>
<div class='col-12'>
Lesson Item: <a href='{{ object.get_absolute_url }}'>{{ object.title }}</a>
</div>
</div>
{% elif klass == 'Profile' %}
<div class='row'>
<div class='col-12'>
Lesson Item: <a href='{{ object.get_absolute_url }}'>{{ object.title }}</a>
</div>
</div>
{% else %}
<div class='row'>
<div class='col-12 col-lg-8 offset-lg-4'>
{# <a href='{{ object.get_absolute_url }}'>{{ object }} | {{ object|class_name }}</a>#}
<a href='/{{ object.tutorial_slug }}'>{{ object }}</a>
</div>
</div>
{% endif %}
{% endwith %}
{% endfor %}
url.py
urlpatterns = [
path('search/', views.SearchView.as_view()),
]
now run in browser http://127.0.0.1:8000/search/
How to create a rest api using django
Dec. 19, 2019, 9:47 a.m.
279How to Create a RESTful API Using Django
# Install Django REST framework into the virtual environment
pip install djangorestframework
models.py
from django.db import models
class MYtutorial(models.Model):
tutorial_title = models.CharField(max_length=200)
tutorial_content = RichTextUploadingField()
Now create serializers.py inside your apps,where models.py there.
serializers.py
from rest_framework import serializers
from .models import Mytutorial
class rest_tutorials(serializers.ModelSerializer):
class Meta:
model = Mytutorial
fields = 'tutorial_title', 'tutorial_content'
views.py
from .models import MYtutorial
# rest api
from rest_framework.views import APIView
from django.http import JsonResponse
from kwiklapp.serializers import rest_tutorials
# rest api
class rest_test(APIView):
def get(self, request):
alltutorials = MYtutorial.objects.all()
serilizer = rest_tutorials(alltutorials, many=True)
return JsonResponse(serilizer.data, safe=False)
urls.py
from django.contrib import admin
from django.urls import path
from kwikl3arnapp import views
from django.conf.urls import url, includ
urlpatterns = [
path('admin/',admin.site.urls),
path('test_api/', views.rest_test.as_view()),
]
now run in browser http://127.0.0.1:8000/test_api/ then you can see output like this
[
{
"tutorial_title": "jquery",
"tutorial_content": "how to use jquery"
},
{
"tutorial_title": "Django",
"tutorial_content": "what is django"
}
]
Note:insert some conent in model that you created other wise you dont see output
Generating random text in django template
Dec. 14, 2019, 4:01 p.m.
273Generating Random text in django template
We can generate random text in Django templates. This is used to fill the sample data.
Django provides inbuilt template tag {% lorem %}
for this.
To generate one paragraph with lorem ipsum text, use the above tag as it
is.
<!-- Lorem ipsum paramgraph -->
{% lorem %}
Output
<!-- Lorem ipsum paramgraph -->
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
To generate let's say 2 paragraphs with random text, use tag with parameters.
<!-- random text paragraph -->
{% lorem 2 b %}
Output
<!-- random text paragraph -->
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Deserunt quisquam dolores minus tempore aperiam itaque minima maxime, atque aperiam libero recusandae quod aliquid sed quo a deserunt, a at rem? Incidunt aut quibusdam est distinctio amet nemo, beatae dolorum fugit corporis recusandae dolorem praesentium vel obcaecati consectetur, voluptas quisquam a neque atque debitis, tenetur eaque nostrum ex?
To generate a few random words, use the tag with below parameters:
<!-- random words of length 10 -->
{% lorem 10 w random %}
Output
<!-- random words of length 10 -->
autem veritatis quisquam optio quibusdam non qui assumenda dolores alias
Customize django admin interface
Dec. 14, 2019, 3:10 p.m.
536customize django admin interface
django-admin-interface is a modern responsive flat admin interface customizable by the admin itself.
Features
- Beautiful default django-theme
- Themes management and customization (you can customize admin title, logo and colors)
- Responsive
- List filter dropdown (optional)
NEW
Related modal (instead of the old popup window, optional)NEW
Environment name/markerNEW
Language chooser- Compatibility / Style optimizations for:
django-ckeditor
django-dynamic-raw-id
django-modeltranslation
django-tabbed-admin
sorl-thumbnail
Requirements
- Python 2.7, 3.4, 3.5, 3.6, 3.7, 3.8
- Django 1.7, 1.8, 1.9, 1.10, 1.11, 2.0, 2.1, 2.2, 3.0
Installation
- Run
pip install django-admin-interface
- Add
admin_interface
,flat_responsive
,flat
andcolorfield
tosettings.INSTALLED_APPS
beforedjango.contrib.admin
INSTALLED_APPS = (
#...
'admin_interface',
'flat_responsive', # only if django version < 2.0
'flat', # only if django version < 1.9
'colorfield',
#...
'django.contrib.admin',
#...
)
- Run
python manage.py migrate
- Run
python manage.py collectstatic
- Restart your application server
Upgrade
- Run
pip install django-admin-interface --upgrade
- Run
python manage.py migrate
(add--fake-initial
if you are upgrading from 0.1.0 version) - Run
python manage.py collectstatic --clear
- Restart your application server
Optional themes
This package ships with optional themes as fixtures, they can be installed using the loaddata admin command. Optional themes are activated on installation.
Django theme (default):
Run python manage.py loaddata admin_interface_theme_django.json
Bootstrap theme:
Run python manage.py loaddata admin_interface_theme_bootstrap.json
Foundation theme:
Run python manage.py loaddata admin_interface_theme_foundation.json
U.S. Web Design Standards theme:
Run python manage.py loaddata admin_interface_theme_uswds.json
Creating a dynamic drop down menu in django
Dec. 14, 2019, 10:44 a.m.
3469creating a dynamic drop down menu in django
models.py
from django.db import models
# Create your models here.
class main_menu(models.Model):
m_menu_id = models.AutoField(primary_key=True)
m_menu_name = models.CharField(max_length=50)
m_menu_link = models.CharField(max_length=100)
class sub_menu(models.Model):
s_menu_id = models.AutoField(primary_key=True)
m_menu_id = models.IntegerField()
s_menu_name = models.CharField(max_length=50)
s_menu_link = models.CharField(max_length=100)
views.py
from django.shortcuts import render, redirect
from django.contrib import auth
from django.contrib.auth import authenticate
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from kwikl3arnapp.models import main_menu, sub_menu
# Create your views here.
def countown(request):
return render(request, 'count.html')
def maninmenu(request):
menu = main_menu.objects.all()
submenu=sub_menu.objects.all()
return render(request, 'menu.html', {'menu': menu,'submenu':submenu})
def mainsave(request):
if request.method == 'POST':
mname = request.POST['menu_name']
mlink = request.POST['mn_link']
main_menu.objects.create(m_menu_name=mname, m_menu_link=mlink)
# return HttpResponse("created")
return redirect('mainmenu')
else:
return redirect('mainmenu')
def subsave(request):
if request.method == 'POST':
menuid=request.POST['parent']
sname=request.POST['sub_menu_name']
slink=request.POST['sub_menu_link']
sub_menu.objects.create(m_menu_id=menuid,s_menu_name=sname,s_menu_link=slink)
return redirect('mainmenu')
else:
return redirect('mainmenu')
def dynamic_menu(request):
menu = main_menu.objects.all()
submenu = sub_menu.objects.all()
return render(request, 'dynamic_menu.html', {'menu': menu, 'submenu': submenu})
urls.py
from django.contrib import admin
from django.urls import path
from kwikl3arnapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.countown, name='countdown'),
path('main',views.maninmenu,name='mainmenu'),
path('mainsave',views.mainsave,name='msave'),
path('submenusave',views.subsave,name='submenusave'),
path('dmenu',views.dynamic_menu,name='dmenu')
]
templates/menu.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="{% url 'msave' %}">
{% csrf_token %}
<input type="text" placeholder="menu name :" name="menu_name"/><br/>
<input type="text" placeholder="menu link :" name="mn_link"/><br/>
<button type="submit" name="add_main_menu">Add main menu</button>
</form>
<table border="1">
<tr>
<th>slno</th>
<th>sitename</th>
<th>sitelink</th>
</tr>
{% for m in menu %}
<tr>
<td>{{ m.m_menu_id }}</td>
<td>{{ m.m_menu_name }}</td>
<td>{{ m.m_menu_link }}</td>
</tr>
{% endfor %}
</table>
<br>
<br>
<h1>-----------------------------------------SUB MENU ADD-------------------------------------------------</h1>
<form method="post" action="{% url 'submenusave' %}">
{% csrf_token %}
<select name="parent">
<option selected="selected">select parent menu</option>
{% for m in menu %}
<option value="{{ m.m_menu_id }}">{{ m.m_menu_name }}</option>
{% endfor %}
</select>
<br/>
<input type="text" placeholder="menu name :" name="sub_menu_name"/><br/>
<input type="text" placeholder="menu link :" name="sub_menu_link"/><br/>
<button type="submit" name="add_sub_menu">Add sub menu</button>
</form>
<table border="1">
<tr>
<th>slno</th>
<th>parent menu id</th>
<th>sitename</th>
<th>sitelink</th>
</tr>
{% for s in submenu %}
<tr>
<td>{{s.s_menu_id }}</td>
<td>{{ s.m_menu_id }}</td>
<td>{{ s.s_menu_name }}</td>
<td>{{ s.s_menu_link }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
templates/dynamic_menu.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Dynamic Dropdown Menu using Django</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
body {
font-family: "Comic Sans MS", cursive;
font-size: 15px;
color: #232323;
}
#head {
background: #f9f9f9;
height: 100px;
padding-top: 15px;
border-bottom: 1px solid #d5dce8;
}
.wrap {
width: 1000px;
margin: 0 auto;
}
#head h1 {
float: left;
}
#head a {
float: right;
}
input, select {
width: 300px;
height: 35px;
}
/* nav menu */
#nav {
margin: 0;
padding: 0;
list-style: none;
border-left: 1px solid #d5dce8;
border-right: 1px solid #d5dce8;
border-bottom: 1px solid #d5dce8;
border-bottom-left-radius: 4px;
-moz-border-radius-bottomleft: 4px;
-webkit-border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
-moz-border-radius-bottomright: 4px;
-webkit-border-bottom-right-radius: 4px;
height: 50px;
padding-left: 15px;
padding-right: 15px;
background: #f9f9f9;
}
#nav li {
float: left;
display: block;
background: none;
position: relative;
z-index: 999;
margin: 0 1px;
}
#nav li a {
display: block;
padding: 0;
font-weight: 700;
line-height: 50px;
text-decoration: none;
color: #818ba3;
zoom: 1;
border-left: 1px solid transparent;
border-right: 1px solid transparent;
padding: 0px 12px;
}
#nav li a:hover, #nav li a.hov {
background-color: #fff;
border-left: 1px solid #d5dce8;
border-right: 1px solid #d5dce8;
color: #576482;
}
/* subnav */
#nav ul {
position: absolute;
left: 1px;
display: none;
margin: 0;
padding: 0;
list-style: none;
-moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
-o-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
padding-bottom: 3px;
}
#nav ul li {
width: 180px;
float: left;
border-top: 1px solid #fff;
text-align: left;
}
#nav ul li:hover {
border-left: 0px solid transparent;
border-right: 0px solid transparent;
}
#nav ul a {
display: block;
height: 20px;
line-height: 20px;
padding: 8px 5px;
color: #666;
border-bottom: 1px solid transparent;
text-transform: uppercase;
color: #797979;
font-weight: normal;
}
#nav ul a:hover {
text-decoration: none;
border-right-color: transparent;
border-left-color: transparent;
background: transparent;
color: #4e4e4e;
}
</style>
</head>
<body>
<div id="head">
<div class="wrap"><br/>
<h1><a href="http://www.kwikl3arn.com/">kwikl3arn</a></h1><label><a href="{% url 'mainmenu' %}">add
menu here</a></label>
</div>
</div>
<div class="wrap">
<ul id="nav">
<li><a href="#">Homepage</a></li>
{% for m in menu %}
<li><a href="{{ m.m_menu_link }} ?>">{{ m.m_menu_name }}</a>
<ul>
{% for s in submenu %}
{% if m.m_menu_id == s.m_menu_id %}
<li><a href="{{ s.s_menu_link}}">{{ s.s_menu_name}}</a></li>
{% endif %}
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#nav li').hover(function () {
$('ul', this).slideDown('fast');
}, function () {
$('ul', this).slideUp('fast');
});
});
</script>
</body>
Insert multiples array values in django
Dec. 14, 2019, 10:38 a.m.
149Insert multiples array values in django
models.py
from django.db import models
class test(models.Model):
name = models.TextField()
mail = models.EmailField(blank=True)
mobile = models.CharField(max_length=10, blank=True)
date = models.TimeField(auto_now_add=True)
views.py
from django.shortcuts import render, redirect
from django.contrib import auth
from django.contrib.auth import authenticate
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from kwikl3arn.models import test
def testing(request):
if request.method == 'POST':
print(request.POST)
uname = request.POST.getlist('name[]', '')
umail = request.POST.getlist('mail[]', '')
uphone = request.POST.getlist('phone[]', '')
print(len(uname))
i = 0
while i < len(uname):
names = uname[i]
print(names)
mails = umail[i]
mobiles = uphone[i]
# # this is checking the variable, if variable is null so fill the varable value in database
if names != "" and mails != "" and mobiles != "":
test.objects.create(name=names, mail=mails, mobile=mobiles)
i = i + 1
return HttpResponse('Your Record Has been Saved')
else:
return render(request, 'test.html')
urls.py
from django.contrib import admin
from django.urls import path
from kwikl3arnsite import views
urlpatterns = [
path('admin/', admin.site.urls),
path('test', views.testing, name='test')
]
templates/test.html
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="container">
<form method="post" action="{% url 'test' %}">
{% csrf_token %}
<input type="button" id="addrow" value="Add Row" />
<table id="myTable" class=" table order-list">
<thead>
<tr>
<td>Name</td>
<td>Gmail</td>
<td>Phone</td>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
</tr>
<tr>
</tr>
</tfoot>
</table>
<input type="submit">
</form>
</div>
</body>
</html>
<script>
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $('<tr id="tr'+counter +'" >');
var cols = "";
cols += '<td><input type="text" class="form-control" name="name[]" id="name' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="mail[]" id="mail' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="phone[]" id="phone' + counter + '"/></td>';
{#cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete" onclick="return delme('+ counter +')">' +#}
cols += '</td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
});
</script>
<script>
//delete table row
function delme(id) {
if(id==0)
{
alert("sorry u can't delete this");
return false;
}
$('#name'+id).val('-1');
$('#mail'+id).val('-1');
$('#phone'+id).val('-1');
var result_style = document.getElementById('tr' +id).style;
result_style.display = 'none';
}
</script>
How to install python packages using requirements text file
Dec. 13, 2019, 10:19 p.m.
209How To Install Python Packages Using Requirements Text File
When we develop Python programs, we always need to install and use a lot of third-party library packages. But if we develop same Python program on another new machine, we may need to install all those library packages again. This will waste time and even make error. But PIP has provide a method for us to make batch install same Python packages in different machine easy and simple without errors, this article will tell you how to do it.
1. Collect Current Installed Python Packages.
- First we need to collect all packages that has been installed on current machine. Open a terminal and run
pip freeze
command to do it.
C:\Users\kwikl3arn>pip freeze
Django==2.2.5
pillow==6.21
- From above output, we can see that two packages has been installed in current Windows OS machine.
- Create a text file to save above packages list in it. The text file name is requirements.txt.
C:\Users\kwikl3arn>pip freeze > Requirements.txt
2. Use PIP To Install Python Packages From Requirements.txt File.
PIP install command provide a -r argument, we can provide above requirements.txt file path as the value to the -r argument, then it will install all packages written in the requirements.txt file. Now we will do this in a new virtual Python environment use Python virtualenv module.
1)Install Python virtualven library use pip.
C:\Users\kwikl3arn>pip install --user virtualenv
2)Add a virtual Python environment in current folder. After run below command successfully, there will add a folder my_env in current folder.
C:\Users\kwikl3arn>python -m venv my_env
3)Run my_env / Scripts / activate.bat file in Windows, or $ source my_env/bin/activate in Linux or MacOS to activate the virtual Python environment. Now you will work in my_env virtual environment.
C:\Users\kwikl3arn\my_env\Scripts>activate.bat
4)Run pip freeze
again in the virtual environment, you can see that no Python packages has been installed in it.
(my_env) C:\Users\kwikl3arn\my_env\Scripts>pip freeze
5)Run pip install -r C:\WorkSpace\requirements.txt
in the virtual environment to install all Python packages written in the requirements.txt file.
(my_env) C:\Users\kwikl3arn\my_env\Scripts>pip install -r C:\WorkSpace\requirements.txt
6)Run pip freeze
again in my_env, now it will list the two Python packages installed.
(my_env) C:\Users\kwikl3arn\my_env\Scripts>pip freeze
Django==2.2.5
pillow==6.21
7)Run deactivate
command to quit the Python virtual environment.
(my_env) C:\Users\kwikl3arn\my_env\Scripts>deactivate
C:\Users\kwikl3arn\my_env\Scripts>
How to add http headers in django response
Dec. 13, 2019, 9:29 p.m.
334How To Add Http Headers In Django Response
1. Add Http Response Headers In Django View Function.
The http response header is always added in the Django project view function before return the HttpResponse object to client. So edit the views.py file home_page function as below.
def home_page(request):
# get the django.http.response.HttpResponse object
resp = render(request, 'home_page.html')
# set http response header and value.
resp['Cache-Control'] = 'public,max-age=100000'
resp['Vary'] = 'Accept-Encoding'
#The Cache-Control is per the HTTP 1.1 spec for clients and proxies (and implicitly required by
#some clients next to Expires). The Pragma is per the HTTP 1.0 spec for prehistoric clients. The
#Expires is per the HTTP 1.0 and 1.1 specs for clients and proxies. In HTTP 1.1, the Cache-Control
#takes precedence over Expires, so it's after all for HTTP 1.0 proxies only.
#resp['Cache-Control'] = "no-cache, no-store, must-revalidate" # HTTP 1.1.
#resp['Pragma'] = "no-cache" # HTTP 1.0.
#resp['Expires'] = "0" # Proxies.
# return the HttpResponse object.
return resp
2. Verify The Http Response Header & Values Via Google Chrome Developer Tools.
- Start the Django project application.
- Browse the web url http://127.0.0.1:8000/dept_emp/ in google chrome.
- Right click the page, click Inspect menu item in the popup menu list.
- Click Network tab in chrome inspector window.reload the page again.
- Select web resource in left panel, click Headers tab in right panel. Now you can see the added http response headers Cache-Control : public,max-age=100000 and Vary :Accept-Encoding.
How to create pagination in django dynamically
Dec. 12, 2019, 7:26 a.m.
348How to create Pagination in django dynamically
views.py
first import the Paginator class and models that u created
from blog.models import Post
from django.core.paginator import Paginator
Call the Paginator class object and give it at least two arguments: the items you want to paginate and the number of items you want to see on each page:
paginator = Paginator(posts, 3)
This will instantiate the paginator object that we can use to access the page items.
Get the pagination page number from the request object:
page = request.GET.get('page')
When you request a page, an HttpRequest object is passed to the view. This contains data about the request like the HTTP GET parameters.
In this case we will be sending the page number in the url like this mysite.com/?page=2.
Use the get_page method with the page number to fetch Page object that we will use to access items in any given page:
posts = paginator.get_page(page)
full code in views,py
from django.shortcuts import render
from blog.models import Post
from django.core.paginator import Paginator # < Import the Paginator class
def home(request):
posts = Post.objects.all()
paginator = Paginator(posts, 3) # < 3 is the number of items on each page
page = request.GET.get('page') # < Get the page number
posts = paginator.get_page(page) # < New in 2.0!
return render(request, 'base/home.html', {'posts': posts})
for old versions use this below code in views.py
from django.shortcuts import render
from blog.models import Post
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger # < Import these
def home(request):
posts = Post.objects.all()
paginator = Paginator(posts, 3)
page = request.GET.get('page')
# Handle out of range and invalid page numbers:
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
return render(request, 'base/home.html', {'posts': posts})
method1 in home.html
<div class="pagination">
{% if posts.has_previous %}
<a href="?page=1">First</a>
<a href="?page={{ posts.previous_page_number }}">Previous</a>
{% endif %}
<span>{{ posts.number }}</span>
<span">of</span>
<span>{{ posts.paginator.num_pages }}</span>
{% if posts.has_next %}
<a href="?page={{ posts.next_page_number }}">Next</a>
<a href="?page={{ posts.paginator.num_pages }}">Last</a>
{% endif %}
</div>
output look like this
First Previous 6 of 15 Next Last
method2 in home.html
<div class="pagination">
{% if posts.has_previous %}
<a href="?page=1">First</a>
<a href="?page={{ posts.previous_page_number }}">Previous</a>
{% endif %}
{% for num in posts.paginator.page_range %}
{% if posts.number == num %}
<span>{{ num }}</span>
{% elif num > posts.number|add:'-3' and num < posts.number|add:'3' %}
<a href="?page={{ num }}">{{ num }}</a>
{% endif %}
{% endfor %}
{% if posts.has_next %}
<a href="?page={{ posts.next_page_number }}">Next</a>
<a href="?page={{ posts.paginator.num_pages }}">Last</a>
{% endif %}
</div>
output look like this
First Previous 6 7 8 9 10 Next Last
How to create dynamic sitemap in django
Dec. 12, 2019, 6:22 a.m.
365How to create dynamic sitemap in django
what is sitemap ?
A site map is a list of a website's content designed to help both users and search engines navigate the site.
A site map can be a hierarchical list of pages, an organization chart, or an XML document that provides instructions to search engine crawl bots.
Why sitemaps are required:
XML Sitemaps are important for SEO because they make it easier for Google to find your site's pages—this is important because Google ranks web PAGES, not just websites.
There is no downside of having an XML Sitemap and having one can improve your SEO, so we highly recommend them.
Steps to add Sitemaps to your Django Application:
Create a file sitemap.py
in your app.
Create two different classes in sitemap.py
file, one for static pages and another for Dynamic URLs.
Let's assume your website sell some product where product details are stored in the database.
Once a new product is added to the database, you want that product page to be searchable by search engines. We need to add all such product pages/URLs to sitemaps.
Static Sitemap:
Define a class Article_Sitemap in your sitemap.py
file. Define the mandatory function items in it which will return the list of objects.
These objects will be passed to the location method which will create URL from these objects.
models.py
from django.db import models
from datetime import date
# Create your models here.
from django.utils.datetime_safe import datetime
class Article(models.Model):
full_path = models.TextField()
date_created = models.DateTimeField(default=datetime.now, blank=True)
date_modified = models.DateTimeField(default=datetime.now)
public = models.BooleanField(default=True)
content = models.TextField()
content_formatted = models.TextField()
def __str__(self):
return self.full_path
settings.py
INSTALLED_APPS = [
'siteapp.apps.SiteappConfig',
'django.contrib.staticfiles',
'django.contrib.sites', # < here
'django.contrib.sitemaps', # < here
]
SITE_ID = 1 # < here
Create a new file called sitemaps.py
in the blog app directory. Add a new class called Article_Sitemap
to it:
from django.contrib.sitemaps import Sitemap
from django.urls import reverse
from siteapp.models import Article
# static sitemapp
class Static_Sitemap(Sitemap):
priority = 1.0
changefreq = 'yearly'
def items(self):
return ['about_view', 'contact_view']
def location(self, item):
return reverse(item)
# dynamic sitemap
class Article_Sitemap(Sitemap):
changefreq = "daily"
priority = 0.7
def items(self):
return Article.objects.all()
def location(self, obj):
return obj.full_path
def lastmod(self, obj):
return obj.date_modified
urls.py
from django.contrib import admin
from django.urls import path
from django.contrib.sitemaps.views import sitemap
from mysitemap.sitemaps import Article_Sitemap
from mysitemap.sitemaps import Static_Sitemap
from siteapp import views
sitemaps = {
'article': Article_Sitemap(),
'static': Static_Sitemap(),
}
urlpatterns = [
path('admin/', admin.site.urls),
path('About/', views.about_view, name='about_view'),
path('Contact/', views.contact_view, name='contact_view'),
path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
]
Run migrations:
python manage.py makemigrations
python manage.py migrate
Visit /sitemap.xml
:
you will see something like this
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://kwikl3arn.com/django/INTRO</loc>
<lastmod>2019-11-07</lastmod>
<changefreq>daily</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>http://kwikl3arn.com/What_is_codeigniter</loc>
<lastmod>2019-11-08</lastmod>
<changefreq>daily</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>http://kwikl3arn.com/What_is_django</loc>
<lastmod>2019-11-08</lastmod>
<changefreq>daily</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>http://kwikl3arn.com/What_is_python</loc>
<lastmod>2019-11-08</lastmod>
<changefreq>daily</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>http://kwikl3arn.com/Codeigniter_Installation</loc>
<lastmod>2019-11-09</lastmod>
<changefreq>daily</changefreq>
<priority>0.7</priority>
</url>
</urlset>
views.py
from django.shortcuts import render
# Create your views here.
def about_view(request):
return render(request, 'about.html')
def contact_view(request):
return render(request, 'contact.html')
templates/about.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
about page
</body>
</html>
templates/contact.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
contact
</body>
</html>
Detect devices type with django and python 3
Dec. 9, 2019, 4:56 p.m.
302Detect devices type with Django and Python 3
Django User Agents
A django package that allows easy identification of visitor's browser, OS and device information, including whether the visitor uses a mobile phone, tablet or a touch capable device. Under the hood, it uses user-agents.
Installation
-
Install
django-user-agents
, you'll have to make sure that user-agents is installed first:pip install pyyaml ua-parser user-agents pip install django-user-agents pip install python-memcached
-
Configure
settings.py
:INSTALLED_APPS = ( # Other apps... 'django_user_agents', ) # Cache backend is optional, but recommended to speed up user agent parsing CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } # Name of cache backend to cache user agents. If it not specified default # cache alias will be used. Set to `None` to disable caching. USER_AGENTS_CACHE = 'default'
Usage
Middleware
Add UserAgentMiddleware
in settings.py
:
MIDDLEWARE_CLASSES = (
# other middlewares...
'django_user_agents.middleware.UserAgentMiddleware',
)
A user_agent
attribute will now be added to request
, which you can use in views.py
:
def my_view(request):
# Let's assume that the visitor uses an iPhone...
request.user_agent.is_mobile # returns True
request.user_agent.is_tablet # returns False
request.user_agent.is_touch_capable # returns True
request.user_agent.is_pc # returns False
request.user_agent.is_bot # returns False
# Accessing user agent's browser attributes
request.user_agent.browser # returns Browser(family=u'Mobile Safari', version=(5, 1), version_string='5.1')
request.user_agent.browser.family # returns 'Mobile Safari'
request.user_agent.browser.version # returns (5, 1)
request.user_agent.browser.version_string # returns '5.1'
# Operating System properties
request.user_agent.os # returns OperatingSystem(family=u'iOS', version=(5, 1), version_string='5.1')
request.user_agent.os.family # returns 'iOS'
request.user_agent.os.version # returns (5, 1)
request.user_agent.os.version_string # returns '5.1'
# Device properties
request.user_agent.device # returns Device(family='iPhone')
request.user_agent.device.family # returns 'iPhone'
If you have django.core.context_processors.request
enabled, user_agent
will also be available in template through request
:
{% if request.user_agent.is_mobile %}
Do stuff here...
{% endif %}
View Usage
django-user_agents
comes with get_user_agent
which takes a single request
argument and returns a UserAgent
instance. Example usage:
from django_user_agents.utils import get_user_agent
def my_view(request):
user_agent = get_user_agent(request)
if user_agent.is_mobile:
# Do stuff here...
elif user_agent.is_tablet:
# Do other stuff...
Template Usage
django-user_agents
comes with a few template filters:
is_mobile
is_tablet
is_touch_capable
is_pc
is_bot
You can use all of these like any other django template filters:
{% load user_agents %}
{% if request|is_mobile %}
Mobile device stuff...
{% endif %}
{% if request|is_tablet %}
Tablet stuff...
{% endif %}
{% if request|is_pc %}
PC stuff...
{% endif %}
{% if request|is_touch_capable %}
Touch capable device stuff...
{% endif %}
{% if request|is_bot %}
Bot stuff...
{% endif %}
Django database optimizations
Dec. 7, 2019, 8:39 p.m.
177Django database optimizations
1)Accessing Foreign Key Values
If you only need the ID of the Foreign Key:
correct:
post.author_id
wrong:
post.author.id
If you have a foreign key named author, Django will automatically store the primary key in the property author_id, while in the author property will be stored a lazy database reference. So if you access the id via the author instance, like this post.author.id
, it will cause an additional query.
2)Bulk Insert on Many to Many Fields
correct:
user.groups.add(administrators, managers)
wrong:
user.groups.add(administrators)
user.groups.add(managers)
3)Counting QuerySets
correct:
users = User.objects.all()
users.count()
# Or in template...
{{ users.count }}
wrong:
users = User.objects.all()
len(users)
# Or in template...
{{ users|length }}
4)Empty QuerySets
correct:
groups = Group.objects.all()
if groups.exists():
# Do something...
wrong:
groups = Group.objects.all()
if groups:
# Do something...
5)Reduce Query Counts
correct:
review = Review.objects.select_related('author').first() # Select the Review and the Author in a single query
name = review.author.first_name
wrong:
review = Review.objects.first() # Select the Review
name = review.author.first_name # Additional query to select the Author
6)Select Only What You Need
Let’s say the Invoice model has 50 fields and you want to create a view to display just a summary, with the number, date and value:
correct:
# views.py
# If you don't need the model instance, go for:
invoices = Invoice.objects.values('number', 'date', 'value') # Returns a dict
# If you still need to access some instance methods, go for:
invoices = Invoice.objects.only('number', 'date', 'value') # Returns a query set
# invoices.html
<table>
{% for invoice in invoices %}
<tr>
<td>{{ invoice.number }}</td>
<td>{{ invoice.date }}</td>
<td>{{ invoice.value }}</td>
</tr>
{% endfor %}
</table>
wrong:
# views.py
invoices = Invoice.objects.all()
# invoices.html
<table>
{% for invoice in invoices %}
<tr>
<td>{{ invoice.number }}</td>
<td>{{ invoice.date }}</td>
<td>{{ invoice.value }}</td>
</tr>
{% endfor %}
</table>
7)Bulk Updates
correct:
from django.db.models import F
Product.objects.update(price=F('price') * 1.2)
wrong:
products = Product.objects.all()
for product in products:
product.price *= 1.2
product.save()
How to reset migrations in django
Dec. 3, 2019, 7:25 a.m.
267How to Reset Migrations in Django
Method1:
The project is still in the development environment and you want to perform a full clean up. You don’t mind throwing the whole database away.
1. Remove the all migrations files within your project
Go through each of your projects apps migration folder and remove everything inside, except the __init__.py file
Or if you are using a unix-like OS you can run the following script (inside your project dir):
find . -path "*/migrations/*.py" -not -name "__init__.py" -delete
find . -path "*/migrations/*.pyc" -delete
2. Drop the current database.
3. Create the initial migrations and generate the database schema:
python manage.py makemigrations
python manage.py migrate
Done
Method2:
You want to clear all the migration history but you want to keep the existing database.
1. Make sure your models fits the current database schema
The easiest way to do it is trying to create new migrations:
python manage.py makemigrations
If there are any pending migration, apply them first.
If you see the message:
No changes detected
You are good to go.
2. Clear the migration history for each app
Now you will need to clear the migration history app by app.
First run the showmigrations
command so we can keep track of what is going on:
python manage.py showmigrations
Result will be something like this as shown below
admin
[X] 0001_initial
[X] 0002_logentry_remove_auto_add
auth
[X] 0001_initial
[X] 0002_alter_permission_name_max_length
[X] 0003_alter_user_email_max_length
[X] 0004_alter_user_username_opts
[X] 0005_alter_user_last_login_null
[X] 0006_require_contenttypes_0002
[X] 0007_alter_validators_add_error_messages
contenttypes
[X] 0001_initial
[X] 0002_remove_content_type_name
core
[X] 0001_initial
[X] 0002_remove_mymodel_i
[X] 0003_mymodel_bio
sessions
[X] 0001_initial
Clear the migration history (please note that kwikl3arn is the name of my app):
python manage.py migrate --fake kwikl3arn zero
The result will be something like this:
Operations to perform:
Unapply all migrations: core
Running migrations:
Rendering model states... DONE
Unapplying core.0003_mymodel_bio... FAKED
Unapplying core.0002_remove_mymodel_i... FAKED
Unapplying core.0001_initial... FAKED
Now run the command showmigrations
again:
python manage.py showmigrations
Now Result will be look like this
admin
[X] 0001_initial
[X] 0002_logentry_remove_auto_add
auth
[X] 0001_initial
[X] 0002_alter_permission_name_max_length
[X] 0003_alter_user_email_max_length
[X] 0004_alter_user_username_opts
[X] 0005_alter_user_last_login_null
[X] 0006_require_contenttypes_0002
[X] 0007_alter_validators_add_error_messages
contenttypes
[X] 0001_initial
[X] 0002_remove_content_type_name
core
[ ] 0001_initial
[ ] 0002_remove_mymodel_i
[ ] 0003_mymodel_bio
sessions
[X] 0001_initial
You must do that for all the apps you want to reset the migration history.
3. Remove the actual migration files.
Go through each of your projects apps migration folder and remove everything inside, except for the __init__.py
file.
Or if you are using a unix-like OS you can run the following script (inside your project dir):
find . -path "*/migrations/*.py" -not -name "__init__.py" -delete
find . -path "*/migrations/*.pyc" -delete
NOTE: The example above will remove all the migrations file inside your project.
Run the showmigrations
again:
python manage.py showmigrations
Now Result will be look like this
admin
[X] 0001_initial
[X] 0002_logentry_remove_auto_add
auth
[X] 0001_initial
[X] 0002_alter_permission_name_max_length
[X] 0003_alter_user_email_max_length
[X] 0004_alter_user_username_opts
[X] 0005_alter_user_last_login_null
[X] 0006_require_contenttypes_0002
[X] 0007_alter_validators_add_error_messages
contenttypes
[X] 0001_initial
[X] 0002_remove_content_type_name
core
(no migrations)
sessions
[X] 0001_initial
4. Create the initial migrations
python manage.py makemigrations
Now Result will be look like this
Migrations for 'kwikl3arn':
0001_initial.py:
- Create model MyModel
5. Fake the initial migration
In this case you won’t be able to apply the initial migration because the database table already exists. What we want to do is to fake this migration instead:
python manage.py migrate --fake-initial
Now Result will be look like this
Operations to perform:
Apply all migrations: admin, core, contenttypes, auth, sessions
Running migrations:
Rendering model states... DONE
Applying core.0001_initial... FAKED
Run showmigrations
again:
admin
[X] 0001_initial
[X] 0002_logentry_remove_auto_add
auth
[X] 0001_initial
[X] 0002_alter_permission_name_max_length
[X] 0003_alter_user_email_max_length
[X] 0004_alter_user_username_opts
[X] 0005_alter_user_last_login_null
[X] 0006_require_contenttypes_0002
[X] 0007_alter_validators_add_error_messages
contenttypes
[X] 0001_initial
[X] 0002_remove_content_type_name
core
[X] 0001_initial
sessions
[X] 0001_initial
we are done
Django run localhost from another computer connected to another network
Dec. 2, 2019, 5:18 p.m.
4804Django run localhost from another computer connected to another network
Run server with local host or your system IP like one of the below
python manage.py runserver 192.168.6.7:8000
python manage.py runserver 0.0.0.0:8000
python manage.py runserver 127.0.0.1:8000
add hosts in settings.py to access from other system in network.
ALLOWED_HOSTS = ['127.0.0.1', 'localhost','192.168.6.7']