Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

Creating Django Project With Example

Install Virtualenv
Virtualenv is a tool to create isolated Python environments. It's not mandatory, but it's a good practice to
use it to avoid conflicts between different projects.

pip install virtualenv

Create a Virtual Environment


Create a new directory for your Django project and navigate to it in the command prompt. Then, create a
virtual environment by running:
1. mkdir mydir (Create directory either in c or d or E drive)
2. cd mydir
3. Activate the virtual environment: env\Scripts\activate

Install Django
With your virtual environment activated, you can now install Django using pip:

pip install django

Start a New Django Project


django-admin startproject myproject
Replace "myproject" with the name you want for your Django project.

Run the Development Server


python manage.py runserver

Example:
To create your app, make sure you’re in the same directory as manage.py and type this command:

python manage.py startapp polls

Write your first view

Let’s write the first view. Open the file polls/views.py and put the following Python code in it:
polls/views.py

from django.http import HttpResponse

def index(request):
return HttpResponse("Hello, world. You're at the polls index.")

This is the simplest view possible in Django. To call the view, we need to map it to a URL - and for this we
need a URLconf.

polls/urls.py

from django.urls import path

from . import views

urlpatterns = [
path('', views.index, name='index'),
]

The next step is to point the root URLconf at the polls.urls module

mysite/urls.py

from django.contrib import admin


from django.urls import include, path

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

Errors in Django

Common Django Errors and Debugging Tips


1. Template Errors
Issues in HTML templates:

Syntax errors: Incorrect HTML or template tags.


Undefined variables: Using variables not passed from the view.
Debugging: Check error messages for line numbers and consult the Django documentation
for correct syntax.

2. View Errors
Problems in view functions:

Syntax errors: Mistakes in Python code.


Unhandled exceptions: Errors not caught by try-except blocks.
Debugging: Review the error traceback and use a debugger to step through the code.

3. URL Resolution Errors


Django can't find a matching URL pattern:

Typos: Misspelled URL patterns.


Incorrect regex: Faulty regular expressions.
Conflicts: Overlapping URL patterns.
Debugging: Check the error message for attempted patterns and review your URLconf.

4. Database Errors
Issues with database interactions:

Incorrect credentials: Wrong database settings.


Invalid SQL: Mistakes in raw SQL queries.
Schema issues: Problems with migrations.
Debugging: Verify settings and review SQL syntax.

5. Server Errors
General server issues:

Misconfiguration: Incorrect server settings.


Memory issues: Running out of resources.
Permission problems: Incorrect file permissions.
Debugging: Check server logs and adjust configurations and permissions as needed.

General Debugging Tips


Consult Error Messages: Detailed messages specify the error and location.
Use Django Debug Mode: Set DEBUG to True for detailed error pages in development.
Check Django Documentation: Offers explanations and solutions for common errors.
Use a Debugger: Tools like PyCharm or pdb help inspect variables and step through code.
Example: Debugging a 404 Error
To debug a 404 error:

Run the server: python manage.py runserver


Access a non-existent URL: http://127.0.0.1:8000/does-not-exist/
Django will display a “Page not found” message with details on the URLconf and patterns
attempted, helping you identify why the URL threw a 404 error..
Figure 1.4 Error in Django

MODULE-2
Template-System Basics

Template-System Basics in Django

1. What is a Django Template?

 A Django template is a string of text used to separate the presentation of a document from its data.
 It includes placeholders and basic logic (template tags) to control how the document is displayed.
 Templates are typically used to produce HTML but can generate any text-based format.

2. Example Template:

- An HTML page template thanking a person for placing an order:

<!DOCTYPE html>
<html>
<head>
<title>Greeting Page</title>
</head>
<body>
<h1>Welcome! </h1>
<p>Hello, {{ user_name }}!</p>
<p>Today is {{current_date|date:"F j, Y”}}. </p>
{% if is_member %}
<p>Thanks for being a member! </p>
{% else %}
<p>Consider joining our membership program for exclusive benefits. </p>
{% endif %}
</body>
</html>

3. Variables:

 Surrounded by double curly braces, e.g., `{{person_name}} `.


 Placeholders for values that will be provided later.

4. Template Tags:

 Surrounded by curly braces and percent signs, e.g., `{% if ordered_warranty %}`.
 Direct the template system to perform actions, such as loops and conditionals.
 Example tags:
 `{% for item in item_list %}`: Loops over items.
 `{% if ordered_warranty %}`: Conditional logic.

5. Filters:
 Modify the formatting of variables.
 Example: `{{ship_date|date:"F j, Y" }}` uses the `date` filter to format `ship_date`.
 Filters are attached using a pipe character (`|`).

Tags and Filters in Django

Filters

Filters in Django templates are used to modify the value of a variable before it gets displayed. They are
simple functions that take an input value and return a modified output. Filters are attached to variables
using a pipe character (`|`).

Common Filters:

1. `date`: Formats a date according to the given format.


```html
{{ current_date|date:"F j, Y" }}
```
- Example: If `current_date` is `2024-05-26`, the output will be "May 26, 2024".

2. `upper`: Converts a string to uppercase.


```html
{{ user_name|upper }}
```
- Example: If `user_name` is "John Doe", the output will be "JOHN DOE".

3. `length`: Returns the length of a list or string.


```html
{{ item_list|length }}
```
- Example: If `item_list` is `[item1, item2]`, the output will be `2`.

4. `default`: Provides a default value if the variable is empty or doesnt exist.


```html
{{ user_name|default:"Guest" }}
```
- Example: If `user_name` is empty, the output will be "Guest".

5. `lower`: Converts a string to lowercase.


```html
{{ user_name|lower }}
```
- Example: If `user_name` is "John Doe", the output will be "john doe".

Tags

Tags in Django templates provide logic and control flow capabilities. They are more complex than filters and
can do things like loop through data, perform conditional operations, and more. Tags are surrounded by `{%
%}`.

Common Tags:

1. `for`: Iterates over a sequence (like a list or queryset).


```html
<ul>
{% for item in item_list %}
<li>{{ item }}</li>
{% endfor %}
</ul>
```
- Loops through each item in `item_list` and displays it in a list.

2. `if`: Evaluates a condition and includes the enclosed template code only if the condition is true.
```html
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}
```
- Checks if `user.is_authenticated` is true and displays the appropriate message.

3. `block` and `endblock`: Used in template inheritance to define blocks of content that child templates can
override.
```html
{% block content %}
<p>This is the default content.</p>
{% endblock %}
```
- Defines a block of content that can be replaced in child templates.

4. `extends`: Indicates that a template inherits from a parent template.


```html
{% extends "base.html" %}
```
- Inherits content from `base.html`.

5. `include`: Includes another template and renders it in the current template.


```html
{% include "navbar.html" %}
```
- Embeds the content of `navbar.html` in the current template.
Program Hello World:

To create your app, make sure you’re in the same directory as manage.py and type this command:

python manage.py startapp polls

Write your first view


Let’s write the first view. Open the file polls/views.py and put the following Python code in it:

polls/views.py

from django.http import HttpResponse

def index(request):
return HttpResponse("Hello, world. You're at the polls index.")

This is the simplest view possible in Django. To call the view, we need to map it to a URL - and for this we
need a URLconf.

polls/urls.py

from django.urls import path

from . import views

urlpatterns = [
path('', views.index, name='index'),
]

The next step is to point the root URLconf at the polls.urls module

mysite/urls.py

from django.contrib import admin


from django.urls import include, path

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

Program DateTime:

1. Develop a Django app that displays current date and time in server.
Step 1: Create a Django App named myapp.
Step 2: Define a View: Open the views.py file inside your myapp directory and define a view to display
the current date and time.

from django.http
import HttpResponse from datetime import datetime
def current_datetime(request):
now = datetime.now()
html = f"<html>
<body>
<h1>Current Date and Time:</h1>
<p>{now}</p>
</body>
</html>"
return HttpResponse(html)

Step 3: Create a URL Configuration: Open the urls.py file inside your myapp directory and create a URL
configuration to map the view you just defined to a URL.

from django.urls import path from . import views


urlpatterns = [ path('current_datetime/', views.current_datetime, name='current_datetime'), ]

Step 4: Update Project URL Configuration: Open the urls.py file inside your project directory
from django.contrib import admin
from django.urls import path, include # Import include

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


path('myapp/', include('myapp.urls')), # Include your app's URLs ]

You might also like