0% found this document useful (0 votes)
24 views

Assignment Question Django

Required

Uploaded by

Anonymous
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Assignment Question Django

Required

Uploaded by

Anonymous
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Assignment question 2

1. Request Arrival:
o When a user makes an HTTP request (http://127.0.0.1:8000/hello/), Django’s
server receives the request.
2. Settings File Lookup:
o Django starts by looking for a settings file (setting.py) in the same directory
as the main script (manage.py).
o The settings file contains various configurations for the Django project,
including uppercase settings like TEMPLATE_DIRS, DATABASE_NAME etc.
3. URLconf Determination:
o The most crucial setting in the settings file is ROOT_URLCONF.ROOT_URLCONF
o ROOT_URLCONF.ROOT_URLCONF specifies which Python module should be used
as the URL configuration (URLconf) for this particular website.
4. URL Pattern Matching:
o Django loads the URL configuration (ROOT_URLCONF) pointed to by URLS.PY
o It examines each URL pattern in the URL configuration sequentially.
o For each pattern, Django compares the requested URL (e.g., /hello/) with the
pattern.
o If it finds a matching pattern, it proceeds to the associated view function.
5. View Function Invocation:
o When a matching pattern is found, Django calls the view function associated
with that pattern.
o The view function receives an HttpResponse object (representing the
request) as its first parameter.
o The view function processes the request (e.g., handling form submissions,
database queries, etc.).
6. Response Generation:
o The view function must return an HttpResponse (HTTP response).
o Once the view function returns the response, Django takes over.
o Django converts the Python object (the response) into a proper HTTP
response.
o This includes setting the appropriate HTTP headers and constructing the body
(content) of the web page.
7. Final Result:
o The properly formatted HTTP response is sent back to the client’s browser.
o The browser displays the web page based on the response received.

Assignment q3:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Assignment</title>
</head>
<body>
<h1>Table of {{num1}} from 1 to {{num2}}</h1>

{% for i in table%}

<p>{{i}}</p>
{%endfor %}

</body>
</html>

from django.shortcuts import render

def Table(request,offset1,offset2):
table = []
table2=[]
for i in range(1, offset2+1):
result = offset1 i
table.append((offset1,i, result))

for i in table:
table2.append(f"{i[0]} {i[1]} = {i[2]}")

return render(request,
'assign.html',{'num1':offset1,'num2':offset2,'table':table2})

from django.urls import path


from .import views

urlpatterns = [
path('table/<int:offset1>/<int:offset2>', views.Table,),

from django.contrib import admin


from django.urls import path,include
from .import views
urlpatterns = [
path('',include('assignment.urls'))]

Assign q4

<!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>
<h1>Number of Vowels in {{word}} is {{num_vowels}}</h1>
{% for v in vowels_list%}
<p>{{v}}</p>
{% endfor %}

<h1>number of consonents in the {{word}} is {{num_consonants}}</h1>


{% for c in consonants%}
<p>{{c}}</p>
{% endfor %}

</body>
</html>

from django.shortcuts import render

def Word(request,words):
vowels = "aeiouAEIOU"
consonants = []
vowel_list = []

for char in words:


if char.isalpha(): # Check if character is a letter
if char in vowels:
vowel_list.append(char)
else:
consonants.append(char)

num_vowels = len(vowel_list)
num_consonants = len(consonants)

return
render(request,'words.html',{'word':words,'num_vowels':num_vowels,'num_consona
nts':num_consonants,'consonants':consonants, 'vowels_list':vowel_list})

from django.urls import path


from .import views

urlpatterns = [
path('table/<str:words>', views.Word),
]
from django.contrib import admin
from django.urls import path,include
from .import views
urlpatterns = [
path('',include('assignment.urls'))]

q5

Django’s error page

1. Exception Details:
o At the top of the page, you’ll find essential information about the exception:
▪ The type of exception (e.g., “unsupported type” in this case).
▪ Any parameters associated with the exception.
▪ The file where the exception occurred.
▪ The specific line number that triggered the exception.
2. Python Traceback:
o Below the exception details, you’ll see a complete Python traceback.
o Each level (or “frame”) in the stack is displayed:
▪ File name.
▪ Function/method name.
▪ Line number.
▪ Source code snippet for that frame.
3. Source Code Context:
o Clicking on a source code line (in dark gray) reveals additional lines before
and after the erroneous line.
o This context helps you understand the surrounding code.
4. Local Variables:
o Under each frame, you can click “Local vars” to view local variables and their
values at the exact point of the exception.
o This debugging information is valuable for diagnosing issues.
5. Copy-and-Paste View:
o The “Switch to copy-and-paste view” option provides an alternate traceback
format that’s easy to copy and share.
6. Sharing Traceback:
o The “Share this traceback on a public Web site” button posts the traceback to a
public site (e.g., http://www.dpaste.com/).
o You’ll receive a distinct URL to share with others for technical support.
7. Request Information:
o The “Request information” section includes details about the incoming Web
request:
▪ GET and POST data.
▪ Cookie values.
▪ CGI headers.
8. Django Settings:
o The “Settings” section lists all settings for this Django installation.
o These settings impact the behavior of your application.
Q6 Method call something something

Method Call Behavior in Templates

Method-call behavior in templates, such as in Django, is more intricate than other types of dot
lookups (like attribute access or dictionary key access). Understanding this behavior is crucial for
safely and effectively using template engines. Here's a detailed note on how method calls work in
templates and how they differ from other dot lookups.

1. Exception Handling:

- If a method raises an exception during lookup, the exception is propagated unless it has an
attribute `silent_variable_failure` set to `True`.

- If the exception does have the `silent_variable_failure` attribute, the variable will render as an
empty string.

Example:

```python

>>> t = Template("My name is {{ person.first_name }}.")

>>> class PersonClass3:

... def first_name(self):

... raise AssertionError("foo")

>>> p = PersonClass3()

>>> t.render(Context({"person": p}))

Traceback (most recent call last):

...

AssertionError: foo

...

>>> class SilentAssertionError(AssertionError):

... silent_variable_failure = True

>>> class PersonClass4:

... def first_name(self):

... raise SilentAssertionError

>>> p = PersonClass4()

>>> t.render(Context({"person": p}))


u'My name is .'

```

2. Argument Requirements:

- A method call will only work if the method has no required arguments. If arguments are required,
the system will skip the method and move to the next lookup type (such as list-index lookup).

3. Side Effects and Security:

- Some methods have side effects (e.g., modifying data), which can pose security risks if executed
inadvertently through a template.

- For instance, a `delete()` method on a `BankAccount` object could potentially delete the account if
accessed through a template, which would be unsafe.

4. Preventing Execution of Methods with Side Effects:

- To prevent the template system from executing methods that alter data, the method should have
the attribute `alters_data` set to `True`.

Example:

```python

def delete(self):

# Delete the account

delete.alters_data = True

```

- If a method is marked with `alters_data=True`, the template system will not execute it. Instead, it
will fail silently if attempted to be accessed through the template.

Continuing the example:

```python

>>> class BankAccount:

... def delete(self):

... delete.alters_data = True

>>> account = BankAccount()

>>> t = Template("{{ account.delete }}")

>>> t.render(Context({"account": account}))


u''

```

### Differences from Other Dot Lookups

1. Attributes:

- Attribute lookups are straightforward; they directly access the value of the attribute without
execution.

- Example:

```python

{{ person.first_name }}

```

2. Dictionary Keys:

- Dictionary key lookups access values based on keys directly.

- Example:

```python

{{ my_dict.key }}

```

3. Methods:

- Method lookups involve calling the method and using the return value.

- If a method raises an exception and doesn't have `silent_variable_failure=True`, the exception is


propagated, which is not the case for attribute or dictionary lookups.

- Methods requiring arguments are skipped, while attributes and dictionary keys are always
accessed if they exist.

Q7

Configuring a database in Django involves specifying the necessary settings in the


settings.py file

1. Install the Required Database Adapter:


o Before configuring the database, ensure you have the appropriate database
adapter installed. For PostgreSQL, you’ll need the psycopg2 package. Install
it using pip:
o pip install psycopg2
2. Edit settings.py:
o Open your Django project’s settings.py file.
o Locate the database-related settings section.
3. Database Settings:
oSet the following parameters:
▪ DATABASE_ENGINE: Specify the database engine (e.g.,
'postgresql_psycopg2' for PostgreSQL).
▪ DATABASE_NAME: Provide the name of your database.
▪ DATABASE_USER: Set the username for database access.
▪ DATABASE_PASSWORD: Set the password for the specified user.
▪ DATABASE_HOST: Specify the database host (usually 'localhost').
▪ DATABASE_PORT: Set the port number for database communication
(e.g., '5432' for PostgreSQL).
4. Example Configuration for PostgreSQL:
o DATABASES = {
o 'default': {
o 'ENGINE': 'django.db.backends.postgresql_psycopg2',
o 'NAME': 'mydb',
o 'USER': 'myuser',
o 'PASSWORD': 'mypassword',
o 'HOST': 'localhost',
o 'PORT': '5432',
o }
o }
5. Testing Configuration:
o Run the following command to test your database configuration:
o python manage.py shell
o
In the shell, execute database-related commands to verify the connection.
6. Common Errors:
o If you encounter any errors, check the error message for clues. Common issues
include incorrect credentials or missing database adapters.

Q8

Template Inheritance in Web Development


Template inheritance is a powerful feature in web frameworks like Django that allows you
to create a consistent structure for your web pages while still allowing customization. Instead
of duplicating common HTML code across multiple pages, you define a base template with
shared elements and placeholders. Child templates then extend or override specific parts of
this base template.

Here’s how it works:

1. Base Template (Skeleton):


o You create a base template (often called a “skeleton” template) that contains
the common structure of your site. This template includes placeholders
(blocks) for dynamic content.
o In Django, you define blocks using {% block %} tags. These blocks represent
areas where child templates can insert their own content.
2. Child Templates (Specific Pages):
o Each specific page (e.g., homepage, about page, product details) becomes a
child template.
o Child templates extend the base template using the {% extends %} tag. This
establishes a parent-child relationship.
oWithin a child template, you can override specific blocks from the base
template by defining content within matching {% block %} tags.
3. Example: Base Template and Child Template:
o Let’s say we have a base template called base.html:
o <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
o <html lang="en">
o <head>
o <title>{% block title %}My Website{% endblock %}</title>
o </head>
o <body>
o <h1>Welcome to my site</h1>
o {% block content %}{% endblock %}
o <p>Thanks for visiting!</p>
o </body>
o </html>
o And a child template called homepage.html:
o {% extends "base.html" %}
o
o {% block title %}Home - My Website{% endblock %}
o
o {% block content %}
o <p>This is the homepage content.</p>
o {% endblock %}
o In this example:
▪ The homepage.html template extends base.html.
▪ It overrides the title block to set a custom title.
▪ The content block adds specific content for the homepage.
4. Benefits:
o Consistent layout: The base template ensures a consistent look and feel across
all pages.
o Customization: Child templates can focus on specific content without
repeating common elements.
o Easy updates: If you need to change the site header or footer, you only modify
the base template.

You might also like