0% found this document useful (0 votes)
7 views8 pages

Django

The document provides an overview of Django Admin, including how to set up a superuser, register models, and customize the admin interface. It also covers creating and using variables in templates, utilizing QuerySets for database interactions, and implementing static files in Django applications. Additionally, it discusses the use of template tags for logic and the configuration of WhiteNoise for serving static files in production.

Uploaded by

ramkumarlaksh74
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views8 pages

Django

The document provides an overview of Django Admin, including how to set up a superuser, register models, and customize the admin interface. It also covers creating and using variables in templates, utilizing QuerySets for database interactions, and implementing static files in Django applications. Additionally, it discusses the use of template tags for logic and the configuration of WhiteNoise for serving static files in production.

Uploaded by

ramkumarlaksh74
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 8

Django Admin

Django Admin is a really great tool in Django, it is actually a CRUD* user


interface of all your models!

*CRUD stands for Create Read Update Delete.

py manage.py runserver

Project URLS:

from django.contrib import admin


from django.urls import include, path

urlpatterns = [
path('', include('members.urls')),
path('admin/', admin.site.urls),
]

Super User:

py manage.py createsuperuser

py manage.py runserver

127.0.0.1:8000/admin/

Include Member in the Admin Interface


To include the Member model in the admin interface, we have to tell Django that
this model should be visible in the admin interface.

This is done in a file called admin.py, and is located in your app's folder, which
in our case is the members folder.

batch/admin.py:

from django.contrib import admin


from .models import Member

# Register your models here.


admin.site.register(Member)

Set Display:
-----------

from django.db import models

class Member(models.Model):
firstname = models.CharField(max_length=255)
lastname = models.CharField(max_length=255)
phone = models.IntegerField(null=True)
joined_date = models.DateField(null=True)

def __str__(self):
return f"{self.firstname} {self.lastname}"

Admin.py

from django.contrib import admin


from .models import Member
# Register your models here.

class MemberAdmin(admin.ModelAdmin):
list_display = ("firstname", "lastname", "joined_date",)

admin.site.register(Member, MemberAdmin)
-----------------------------------------------------------------------------------
---------------------------------------------------

Django Variables:
----------------

templates/template.html:

<h1>Hello {{ firstname }}, how are you?</h1>

views.py
-------

from django.http import HttpResponse


from django.template import loader

def testing(request):
template = loader.get_template('template.html')
context = {
'firstname': 'Gowtham',
}
return HttpResponse(template.render(context, request))

Create Variables in Template


----------------------------

You can also create variables directly in the template, by using the {% with %}
template tag.

The variable is available until the {% endwith %} tag appears.

{% with firstname="Tobias" %}
<h1>Hello {{ firstname }}, how are you?</h1>
{% endwith %}

Data From Model:


---------------

from django.http import HttpResponse, HttpResponseRedirect


from django.template import loader
from .models import Member

def testing(request):
mymembers = Member.objects.all().values()
template = loader.get_template('template.html')
context = {
'mymembers': mymembers,
}
return HttpResponse(template.render(context, request))

template.html
-------------

<ul>
{% for x in mymembers %}
<li>{{ x.firstname }}</li>
{% endfor %}
</ul>

Template Tags
------------

In Django templates, you can perform programming logic like executing if statements
and for loops.

These keywords, if and for, are called "template tags" in Django.

To execute template tags, we surround them in {% %} brackets.

{% if greeting == 1 %}
<h1>Hello</h1>
{% else %}
<h1>Bye</h1>
{% endif %}

{% if greeting == 1 %}
<h1>Hello</h1>
{% elif greeting == 2 %}
<h1>Welcome</h1>
{% endif %}

{% if greeting == 2 %}
<h1>Hello</h1>
{% endif %}

{% if greeting != 1 %}
<h1>Hello</h1>
{% endif %}

{% if greeting < 3 %}
<h1>Hello</h1>
{% endif %}

{% if greeting <= 3 %}
<h1>Hello</h1>
{% endif %}

{% if greeting == 1 and day == "Friday" %}


<h1>Hello Weekend!</h1>
{% endif %}

{% if greeting == 1 or greeting == 5 %}
<h1>Hello</h1>
{% endif %}

{% if 'Banana' in fruits %}
<h1>Hello</h1>
{% else %}
<h1>Goodbye</h1>
{% endif %}
{% if 'Banana' not in fruits %}
<h1>Hello</h1>
{% else %}
<h1>Goodbye</h1>
{% endif %}

from django.http import HttpResponse


from django.template import loader

def testing(request):
template = loader.get_template('template.html')
context = {
'x': ['Apple', 'Banana', 'Cherry'],
'y': ['Apple', 'Banana', 'Cherry'],
}
return HttpResponse(template.render(context, request))

<ul>
{% for x in mymembers %}
<li>{{ x.firstname }}</li>
{% endfor %}
</ul>

Django QuerySet
---------------

A QuerySet is a collection of data from a database.

A QuerySet is built up as a list of objects.

QuerySets makes it easier to get the data you actually need, by allowing you to
filter and order the data at an early stage.

from django.http import HttpResponse


from django.template import loader
from .models import Member

def testing(request):
mydata = Member.objects.all()
template = loader.get_template('template.html')
context = {
'mymembers': mydata,
}
return HttpResponse(template.render(context, request))

<table border='1'>
<tr>
<th>ID</th>
<th>Firstname</th>
<th>Lastname</th>
</tr>
{% for x in mymembers %}
<tr>
<td>{{ x.id }}</td>
<td>{{ x.firstname }}</td>
<td>{{ x.lastname }}</td>
</tr>
{% endfor %}
</table>

Return Specific Columns


----------------------

The values_list() method allows you to return only the columns that you specify.

from django.http import HttpResponse


from django.template import loader
from .models import Member

def testing(request):
mydata = Member.objects.values_list('firstname')
template = loader.get_template('template.html')
context = {
'mymembers': mydata,
}
return HttpResponse(template.render(context, request))

<!DOCTYPE html>
<html>
<body>

<p>The queryset object:</p>

{{ mymembers }}

<p>Loop through the items:</p>

<table border='1'>
{% for x in mymembers %}
<tr>
<td>{{ x }}</td>
</tr>
{% endfor %}
</table>

</body>
</html>

from django.http import HttpResponse


from django.template import loader
from .models import Member

def testing(request):
mydata = Member.objects.filter(firstname='Emil').values()
template = loader.get_template('template.html')
context = {
'mymembers': mydata,
}
return HttpResponse(template.render(context, request))

<!DOCTYPE html>
<html>
<body>

<p>The queryset object:</p>


{{ mymembers }}

<p>Loop through the items:</p>

<table border='1'>
<tr>
<th>ID</th>
<th>Firstname</th>
<th>Lastname</th>
</tr>
{% for x in mymembers %}
<tr>
<td>{{ x.id }}</td>
<td>{{ x.firstname }}</td>
<td>{{ x.lastname }}</td>
</tr>
{% endfor %}
</table>

</body>
</html>

from django.http import HttpResponse


from django.template import loader
from .models import Member

def testing(request):
mydata = Member.objects.filter(firstname='Emil').values()
template = loader.get_template('template.html')
context = {
'mymembers': mydata,
}
return HttpResponse(template.render(context, request))

<!DOCTYPE html>
<html>
<body>

<p>The queryset object:</p>

{{ mymembers }}

<p>Loop through the items:</p>

<table border='1'>
<tr>
<th>ID</th>
<th>Firstname</th>
<th>Lastname</th>
</tr>
{% for x in mymembers %}
<tr>
<td>{{ x.id }}</td>
<td>{{ x.firstname }}</td>
<td>{{ x.lastname }}</td>
</tr>
{% endfor %}
</table>

</body>
</html>

mydata = Member.objects.filter(lastname='Baskar', id=4).values()

mydata = Member.objects.filter(firstname='Baskar').values() |
Member.objects.filter(firstname='Bharath').values()

mydata = Member.objects.filter(firstname__startswith='L').values()

mydata = Member.objects.all().order_by('firstname').values()

mydata = Member.objects.all().order_by('-firstname').values()

-----------------------------------------------------------------------------------
-------

Create Static Folder

When building web applications, you probably want to add some static files like
images or css files.

Inside the APP


--------------

body {
background-color: lightblue;
font-family: verdana;
}

{% load static %}
And:

<link rel="stylesheet" href="{% static 'myfirst.css' %}">

{% load static %}
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="{% static 'myfirst.css' %}">
<body>

{% for x in fruits %}
<h1>{{ x }}</h1>
{% endfor %}

</body>
</html>

DEBUG = False

ALLOWED_HOSTS = ['*']

WhiteNoise

Django does not have a built-in solution for serving static files, at least not in
production when DEBUG has to be False.

We have to use a third-party solution to accomplish this.

pip install whitenoise

Middleware:

'whitenoise.middleware.WhiteNoiseMiddleware',

STATIC_ROOT = BASE_DIR / 'productionfiles'

STATIC_URL = 'static/'

py manage.py collectstatic

py manage.py runserver

You might also like