Django Admin â Set Fields to Display ”; Previous Next When a model is registered to Djangoâs Admin site, its list of objects is displayed when you click the name of the model. In the following figure, the list of objects in the Employees model is displayed − However, the above page shows the objects in the form Employee object(1), which doesnât reveal the attributes such as the name or contact, etc. To make the object description more user-friendly, we need to override the __str__() method in the employee model class. The employee class is rewritten as below to give the alternate string representation of its object. from django.db import models class Employee(models.Model): empno = models.CharField(max_length=20) empname = models.CharField(max_length=100) contact = models.CharField(max_length=15) salary = models.IntegerField() joined_date = models.DateField(null=True) class Meta: db_table = “employee” def __str__(self): return “Name: {}, Contact: {}”.format(self.empname, self.contact) Make these changes to the model definition, and refresh the admin siteâs homepage (Start the Django server if it isnât already running). Click the Employees model under MYAPP to display the employee object details − If you click any of the object details, a form that shows the object attributes appears, and you can update the object or delete the object from here. You can customize the “change list page” with the “list_display” attribute of an admin.ModelAdmin object that specifies what columns are shown in the change list. The ModelAdmin class is the representation of a model in the admin interface. Usually, these are stored in a file called admin.py in your application. Define the EmployeeAdmin class by inheriting from the ModelAdmin class. Set the list_display attribute as a tuple of the fields to be displayed. from django.contrib import admin # Register your models here. from .models import Employee class EmployeeAdmin(admin.ModelAdmin): list_display = (“empname”, “contact”, “joined_date”) Register the EmployeeAdmin class as follows − admin.site.register(Employee, EmployeeAdmin) You can also register the model using the @admin.register() decorator − from django.contrib import admin # Register your models here. from .models import Employee @admin.register(Employee) class EmployeeAdmin(admin.ModelAdmin): list_display = (“empname”, “contact”, “joined_date”) Save the above changes and refresh the Admin site to display the list of Employee objects − You can also provide a searching facility to the list page. Add search_fields attribute in the EmployeeAdmin class − @admin.register(Employee) class EmployeeAdmin(admin.ModelAdmin): list_display = (“empname”, “contact”, “joined_date”) search_fields = (“empname__startswith”, ) Now the list page shows a search field on the top. The search is based on employeeâs name. The __startswith modifier restricts the search to names that begin with the search parameter. Thus, the Django Admin interface is completely customizable. You can set the fields to be provided in the update form by providing the fields attribute in the admin class. Print Page Previous Next Advertisements ”;
Category: django
Django – Sessions
Django – Sessions ”; Previous Next As discussed earlier, we can use client side cookies to store a lot of useful data for the web app. We have seen before that we can use client side cookies to store various data useful for our web app. This leads to lot of security holes depending on the importance of the data you want to save. For security reasons, Django has a session framework for cookies handling. Sessions are used to abstract the receiving and sending of cookies, data is saved on server side (like in database), and the client side cookie just has a session ID for identification. Sessions are also useful to avoid cases where the user browser is set to ‘not accept’ cookies. Setting Up Sessions In Django, enabling session is done in your project settings.py, by adding some lines to the MIDDLEWARE_CLASSES and the INSTALLED_APPS options. This should be done while creating the project, but it”s always good to know, so MIDDLEWARE_CLASSES should have − ”django.contrib.sessions.middleware.SessionMiddleware” And INSTALLED_APPS should have − ”django.contrib.sessions” By default, Django saves session information in database (django_session table or collection), but you can configure the engine to store information using other ways like: in file or in cache. When session is enabled, every request (first argument of any view in Django) has a session (dict) attribute. Let”s create a simple sample to see how to create and save sessions. We have built a simple login system before (see Django form processing chapter and Django Cookies Handling chapter). Let us save the username in a cookie so, if not signed out, when accessing our login page you won’t see the login form. Basically, let”s make our login system we used in Django Cookies handling more secure, by saving cookies server side. For this, first lets change our login view to save our username cookie server side − def login(request): username = ”not logged in” if request.method == ”POST”: MyLoginForm = LoginForm(request.POST) if MyLoginForm.is_valid(): username = MyLoginForm.cleaned_data[”username”] request.session[”username”] = username else: MyLoginForm = LoginForm() return render(request, ”loggedin.html”, {“username” : username} Then let us create formView view for the login form, where we won’t display the form if cookie is set − def formView(request): if request.session.has_key(”username”): username = request.session[”username”] return render(request, ”loggedin.html”, {“username” : username}) else: return render(request, ”login.html”, {}) Now let us change the url.py file to change the url so it pairs with our new view − from django.conf.urls import patterns, url from django.views.generic import TemplateView urlpatterns = patterns(”myapp.views”, url(r”^connection/”,”formView”, name = ”loginform”), url(r”^login/”, ”login”, name = ”login”)) When accessing /myapp/connection, you will get to see the following page − And you will get redirected to the following page − Now if you try to access /myapp/connection again, you will get redirected to the second screen directly. Let”s create a simple logout view that erases our cookie. def logout(request): try: del request.session[”username”] except: pass return HttpResponse(“<strong>You are logged out.</strong>”) And pair it with a logout URL in myapp/url.py url(r”^logout/”, ”logout”, name = ”logout”), Now, if you access /myapp/logout, you will get the following page − If you access /myapp/connection again, you will get the login form (screen 1). Some More Possible Actions Using Sessions We have seen how to store and access a session, but it”s good to know that the session attribute of the request have some other useful actions like − set_expiry (value) − Sets the expiration time for the session. get_expiry_age() − Returns the number of seconds until this session expires. get_expiry_date() − Returns the date this session will expire. clear_expired() − Removes expired sessions from the session store. get_expire_at_browser_close() − Returns either True or False, depending on whether the user’s session cookies have expired when the user’s web browser is closed. Print Page Previous Next Advertisements ”;
Django – Useful Resources
Django – Useful Resources ”; Previous Next The following resources contain additional information on Django. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Build Python Django Real Project: Django Web Development Best Seller 80 Lectures 10 hours Rathan Kumar More Detail Python Django Web framework: Build your Blog, API Project 33 Lectures 4 hours Chandramouli Jayendran More Detail Angular 12, Python Django & SQLite Full Stack Web Development 5 Lectures 51 mins Vinay Kumar More Detail Angular 12, Python Django and PostgreSQL Full Stack Web Development 5 Lectures 52 mins Vinay Kumar More Detail Django eCommerce | Build Advanced Django Web Application Best Seller 126 Lectures 20.5 hours Rathan Kumar More Detail Django Course in Tamil 21 Lectures 2.5 hours Programming Line More Detail Print Page Previous Next Advertisements ”;
Django – Quick Guide
Django – Quick Guide ”; Previous Next Django – Basics Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Django makes it easier to build better web apps quickly and with less code. Note − Django is a registered trademark of the Django Software Foundation, and is licensed under BSD License. History of Django 2003 − Started by Adrian Holovaty and Simon Willison as an internal project at the Lawrence Journal-World newspaper. 2005 − Released July 2005 and named it Django, after the jazz guitarist Django Reinhardt. 2005 − Mature enough to handle several high-traffic sites. Current − Django is now an open source project with contributors across the world. Django – Design Philosophies Django comes with the following design philosophies − Loosely Coupled − Django aims to make each element of its stack independent of the others. Less Coding − Less code so in turn a quick development. Don”t Repeat Yourself (DRY) − Everything should be developed only in exactly one place instead of repeating it again and again. Fast Development − Django”s philosophy is to do all it can to facilitate hyper-fast development. Clean Design − Django strictly maintains a clean design throughout its own code and makes it easy to follow best web-development practices. Advantages of Django Here are few advantages of using Django which can be listed out here − Object-Relational Mapping (ORM) Support − Django provides a bridge between the data model and the database engine, and supports a large set of database systems including MySQL, Oracle, Postgres, etc. Django also supports NoSQL database through Django-nonrel fork. For now, the only NoSQL databases supported are MongoDB and google app engine. Multilingual Support − Django supports multilingual websites through its built-in internationalization system. So you can develop your website, which would support multiple languages. Framework Support − Django has built-in support for Ajax, RSS, Caching and various other frameworks. Administration GUI − Django provides a nice ready-to-use user interface for administrative activities. Development Environment − Django comes with a lightweight web server to facilitate end-to-end application development and testing. Django – Overview As you already know, Django is a Python web framework. And like most modern framework, Django supports the MVC pattern. First let”s see what is the Model-View-Controller (MVC) pattern, and then we will look at Django’s specificity for the Model-View-Template (MVT) pattern. MVC Pattern When talking about applications that provides UI (web or desktop), we usually talk about MVC architecture. And as the name suggests, MVC pattern is based on three components: Model, View, and Controller. Check our MVC tutorial here to know more. DJANGO MVC – MVT Pattern The Model-View-Template (MVT) is slightly different from MVC. In fact the main difference between the two patterns is that Django itself takes care of the Controller part (Software Code that controls the interactions between the Model and View), leaving us with the template. The template is a HTML file mixed with Django Template Language (DTL). The following diagram illustrates how each of the components of the MVT pattern interacts with each other to serve a user request − The developer provides the Model, the view and the template then just maps it to a URL and Django does the magic to serve it to the user. Django – Environment Django development environment consists of installing and setting up Python, Django, and a Database System. Since Django deals with web application, it”s worth mentioning that you would need a web server setup as well. Step 1 – Installing Python Django is written in 100% pure Python code, so you”ll need to install Python on your system. Latest Django version requires Python 2.6.5 or higher for the 2.6.x branch or higher than 2.7.3 for the 2.7.x branch. If you”re on one of the latest Linux or Mac OS X distribution, you probably already have Python installed. You can verify it by typing python command at a command prompt. If you see something like this, then Python is installed. $ python Python 2.7.5 (default, Jun 17 2014, 18:11:42) [GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux2 Otherwise, you can download and install the latest version of Python from the link http://www.python.org/download. Step 2 – Installing Django Installing Django is very easy, but the steps required for its installation depends on your operating system. Since Python is a platform-independent language, Django has one package that works everywhere regardless of your operating system. You can download the latest version of Django from the link http://www.djangoproject.com/download. UNIX/Linux and Mac OS X Installation You have two ways of installing Django if you are running Linux or Mac OS system − You can use the package manager of your OS, or use easy_install or pip if installed. Install it manually using the official archive you downloaded before. We will cover the second option as the first one depends on your OS distribution. If you have decided to follow the first option, just be careful about the version of Django you are installing. Let”s say you got your archive from the link above, it should be something like Django-x.xx.tar.gz: Extract and install. $ tar xzvf Django-x.xx.tar.gz $ cd Django-x.xx $ sudo python setup.py install You can test your installation by running this command − $ django-admin.py –version If you see the current version of Django printed on the screen, then everything is set. Note − For some version of Django it will be django-admin the “.py” is removed. Windows Installation We assume you have your Django archive and python installed on your computer. First, PATH verification. On some version of windows (windows 7) you might need to make sure the Path system variable has the path the following C:Python27;C:Python27Libsite-packagesdjangobin in it, of course depending on your Python version. Then, extract and install Django. c:>cd c:Django-x.xx Next, install Django by running the following command for which you will need administrative privileges in windows shell “cmd” − c:Django-x.xx>python setup.py install To test your installation, open a
Django – Templates System
Django – Template System ”; Previous Next Django makes it possible to separate python and HTML, the python goes in views and HTML goes in templates. To link the two, Django relies on the render function and the Django Template language. The Render Function This function takes three parameters − Request − The initial request. The path to the template − This is the path relative to the TEMPLATE_DIRS option in the project settings.py variables. Dictionary of parameters − A dictionary that contains all variables needed in the template. This variable can be created or you can use locals() to pass all local variable declared in the view. Django Template Language (DTL) Django’s template engine offers a mini-language to define the user-facing layer of the application. Displaying Variables A variable looks like this: {{variable}}. The template replaces the variable by the variable sent by the view in the third parameter of the render function. Let”s change our hello.html to display today’s date − hello.html <html> <body> Hello World!!!<p>Today is {{today}}</p> </body> </html> Then our view will change to − def hello(request): today = datetime.datetime.now().date() return render(request, “hello.html”, {“today” : today}) We will now get the following output after accessing the URL/myapp/hello − Hello World!!! Today is Sept. 11, 2015 As you have probably noticed, if the variable is not a string, Django will use the __str__ method to display it; and with the same principle you can access an object attribute just like you do it in Python. For example: if we wanted to display the date year, my variable would be: {{today.year}}. Filters They help you modify variables at display time. Filters structure looks like the following: {{var|filters}}. Some examples − {{string|truncatewords:80}} − This filter will truncate the string, so you will see only the first 80 words. {{string|lower}} − Converts the string to lowercase. {{string|escape|linebreaks}} − Escapes string contents, then converts line breaks to tags. You can also set the default for a variable. Tags Tags lets you perform the following operations: if condition, for loop, template inheritance and more. Tag if Just like in Python you can use if, else and elif in your template − <html> <body> Hello World!!!<p>Today is {{today}}</p> We are {% if today.day == 1 %} the first day of month. {% elif today.day == 30 %} the last day of month. {% else %} I don”t know. {%endif%} </body> </html> In this new template, depending on the date of the day, the template will render a certain value. Tag for Just like ”if”, we have the ”for” tag, that works exactly like in Python. Let”s change our hello view to transmit a list to our template − def hello(request): today = datetime.datetime.now().date() daysOfWeek = [”Mon”, ”Tue”, ”Wed”, ”Thu”, ”Fri”, ”Sat”, ”Sun”] return render(request, “hello.html”, {“today” : today, “days_of_week” : daysOfWeek}) The template to display that list using {{ for }} − <html> <body> Hello World!!!<p>Today is {{today}}</p> We are {% if today.day == 1 %} the first day of month. {% elif today.day == 30 %} the last day of month. {% else %} I don”t know. {%endif%} <p> {% for day in days_of_week %} {{day}} </p> {% endfor %} </body> </html> And we should get something like − Hello World!!! Today is Sept. 11, 2015 We are I don”t know. Mon Tue Wed Thu Fri Sat Sun Block and Extend Tags A template system cannot be complete without template inheritance. Meaning when you are designing your templates, you should have a main template with holes that the child”s template will fill according to his own need, like a page might need a special css for the selected tab. Let’s change the hello.html template to inherit from a main_template.html. main_template.html <html> <head> <title> {% block title %}Page Title{% endblock %} </title> </head> <body> {% block content %} Body content {% endblock %} </body> </html> hello.html {% extends “main_template.html” %} {% block title %}My Hello Page{% endblock %} {% block content %} Hello World!!!<p>Today is {{today}}</p> We are {% if today.day == 1 %} the first day of month. {% elif today.day == 30 %} the last day of month. {% else %} I don”t know. {%endif%} <p> {% for day in days_of_week %} {{day}} </p> {% endfor %} {% endblock %} In the above example, on calling /myapp/hello we will still get the same result as before but now we rely on extends and block to refactor our code − In the main_template.html we define blocks using the tag block. The title block will contain the page title and the content block will have the page main content. In home.html we use extends to inherit from the main_template.html then we fill the block define above (content and title). Comment Tag The comment tag helps to define comments into templates, not HTML comments, they won’t appear in HTML page. It can be useful for documentation or just commenting a line of code. Print Page Previous Next Advertisements ”;
Django Admin – Interface
Django – Admin Interface ”; Previous Next Django provides a ready-to-use user interface for administrative activities. We all know how an admin interface is important for a web project. Django automatically generates admin UI based on your project models. Starting the Admin Interface The Admin interface depends on the django.countrib module. To have it working you need to make sure some modules are imported in the INSTALLED_APPS and MIDDLEWARE_CLASSES tuples of the myproject/settings.py file. For INSTALLED_APPS make sure you have − INSTALLED_APPS = ( ”django.contrib.admin”, ”django.contrib.auth”, ”django.contrib.contenttypes”, ”django.contrib.sessions”, ”django.contrib.messages”, ”django.contrib.staticfiles”, ”myapp”, ) For MIDDLEWARE_CLASSES − MIDDLEWARE_CLASSES = ( ”django.contrib.sessions.middleware.SessionMiddleware”, ”django.middleware.common.CommonMiddleware”, ”django.middleware.csrf.CsrfViewMiddleware”, ”django.contrib.auth.middleware.AuthenticationMiddleware”, ”django.contrib.messages.middleware.MessageMiddleware”, ”django.middleware.clickjacking.XFrameOptionsMiddleware”, ) Before launching your server, to access your Admin Interface, you need to initiate the database − $ python manage.py migrate syncdb will create necessary tables or collections depending on your db type, necessary for the admin interface to run. Even if you don”t have a superuser, you will be prompted to create one. If you already have a superuser or have forgotten it, you can always create one using the following code − $ python manage.py createsuperuser Now to start the Admin Interface, we need to make sure we have configured a URL for our admin interface. Open the myproject/url.py and you should have something like − from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns(””, # Examples: # url(r”^$”, ”myproject.views.home”, name = ”home”), # url(r”^blog/”, include(”blog.urls”)), url(r”^admin/”, include(admin.site.urls)), ) Now just run the server. $ python manage.py runserver And your admin interface is accessible at: http://127.0.0.1:8000/admin/ Once connected with your superuser account, you will see the following screen − That interface will let you administrate Django groups and users, and all registered models in your app. The interface gives you the ability to do at least the “CRUD” (Create, Read, Update, Delete) operations on your models. Print Page Previous Next Advertisements ”;
Django Admin â Include Models ”; Previous Next When a new project is initialized with the startproject command, Django automatically installs a few apps, the list of these apps can be found in the INSTALLED_APPS parameter of the projectâs settings module. # Application definition INSTALLED_APPS = [ ”django.contrib.admin”, ”django.contrib.auth”, ”django.contrib.contenttypes”, ”django.contrib.sessions”, ”django.contrib.messages”, ”django.contrib.staticfiles”, ] To be able to log into the admin site, the models â Groups and Users are automatically registered with the Admin site. Hence, as we log into the admin site at the URL http://localhost:8000/admin with the superuser credentials, we get to see the Groups and Users tables on the homepage. However, the models declared in the other apps are not automatically registered. You need to do so in the “admin.py” module present in the appâs package folder. First, we create a new Django app − Python manage.py startapp myapp Next, we include it in the list of INSTALLED_APPS. # Application definition INSTALLED_APPS = [ ”django.contrib.admin”, ”django.contrib.auth”, ”django.contrib.contenttypes”, ”django.contrib.sessions”, ”django.contrib.messages”, ”django.contrib.staticfiles”, ”myapp”, ] All the models to be used are defined in the “models.py” file. Let us define the employee model as follows − from django.db import models # Create your models here. class Employee(models.Model): empno = models.CharField(max_length=20) empname = models.CharField(max_length=100) contact = models.CharField(max_length=15) salary = models.IntegerField() joined_date = models.DateField(null=True) class Meta: db_table = “employee” We must create the migration script and run the migrations. python manage.py makemigrations myapp python manage.py migrate This will now create the Employee model. We now have to add this model to the admin interface. For that, open the “admin.py” file, import the employee model, and call the admin.register() function. from django.contrib import admin # Register your models here. from .models import Employee admin.site.register(Employee) After taking these steps, start the Django server − Python manage.py runserver Open the browser and visit the admin URL http://localhost:8000/admin which will now show the newly registered model under MYAPP. To add new employee objects, click the + Add button − Click the Employees model to expand its collection − The list above shows “Employee object (1)”, “Employee object (2)” without any details as it is the default string representation of the object. In order to display more meaningful representations, we can add a __str__() method in the employee model. Print Page Previous Next Advertisements ”;
Django – Sending E-mails
Django – Sending E-mails ”; Previous Next Django comes with a ready and easy-to-use light engine to send e-mail. Similar to Python you just need an import of smtplib. In Django you just need to import django.core.mail. To start sending e-mail, edit your project settings.py file and set the following options − EMAIL_HOST − smtp server. EMAIL_HOST_USER − Login credential for the smtp server. EMAIL_HOST_PASSWORD − Password credential for the smtp server. EMAIL_PORT − smtp server port. EMAIL_USE_TLS or _SSL − True if secure connection. Sending a Simple E-mail Let”s create a “sendSimpleEmail” view to send a simple e-mail. from django.core.mail import send_mail from django.http import HttpResponse def sendSimpleEmail(request,emailto): res = send_mail(“hello paul”, “comment tu vas?”, “[email protected]”, [emailto]) return HttpResponse(”%s”%res) Here is the details of the parameters of send_mail − subject − E-mail subject. message − E-mail body. from_email − E-mail from. recipient_list − List of receivers’ e-mail address. fail_silently − Bool, if false send_mail will raise an exception in case of error. auth_user − User login if not set in settings.py. auth_password − User password if not set in settings.py. connection − E-mail backend. html_message − (new in Django 1.7) if present, the e-mail will be multipart/alternative. Let”s create a URL to access our view − from django.conf.urls import patterns, url urlpatterns = paterns(”myapp.views”, url(r”^simpleemail/(?P<emailto> [w.%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4})/”, ”sendSimpleEmail” , name = ”sendSimpleEmail”),) So when accessing /myapp/simpleemail/[email protected], you will get the following page − Sending Multiple Mails with send_mass_mail The method returns the number of messages successfully delivered. This is same as send_mail but takes an extra parameter; datatuple, our sendMassEmail view will then be − from django.core.mail import send_mass_mail from django.http import HttpResponse def sendMassEmail(request,emailto): msg1 = (”subject 1”, ”message 1”, ”[email protected]”, [emailto1]) msg2 = (”subject 2”, ”message 2”, ”[email protected]”, [emailto2]) res = send_mass_mail((msg1, msg2), fail_silently = False) return HttpResponse(”%s”%res) Let”s create a URL to access our view − from django.conf.urls import patterns, url urlpatterns = paterns(”myapp.views”, url(r”^massEmail/(?P<emailto1> [w.%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4})/(?P<emailto2> [w.%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4})”, ”sendMassEmail” , name = ”sendMassEmail”),) When accessing /myapp/massemail/[email protected]/[email protected]/, we get − send_mass_mail parameters details are − datatuples − A tuple where each element is like (subject, message, from_email, recipient_list). fail_silently − Bool, if false send_mail will raise an exception in case of error. auth_user − User login if not set in settings.py. auth_password − User password if not set in settings.py. connection − E-mail backend. As you can see in the above image, two messages were sent successfully. Note − In this example we are using Python smtp debuggingserver, that you can launch using − $python -m smtpd -n -c DebuggingServer localhost:1025 This means all your sent e-mails will be printed on stdout, and the dummy server is running on localhost:1025. Sending e-mails to admins and managers using mail_admins and mail_managers methods These methods send e-mails to site administrators as defined in the ADMINS option of the settings.py file, and to site managers as defined in MANAGERS option of the settings.py file. Let”s assume our ADMINS and MANAGERS options look like − ADMINS = ((”polo”, ”[email protected]”),) MANAGERS = ((”popoli”, ”[email protected]”),) from django.core.mail import mail_admins from django.http import HttpResponse def sendAdminsEmail(request): res = mail_admins(”my subject”, ”site is going down.”) return HttpResponse(”%s”%res) The above code will send an e-mail to every admin defined in the ADMINS section. from django.core.mail import mail_managers from django.http import HttpResponse def sendManagersEmail(request): res = mail_managers(”my subject 2”, ”Change date on the site.”) return HttpResponse(”%s”%res) The above code will send an e-mail to every manager defined in the MANAGERS section. Parameters details − Subject − E-mail subject. message − E-mail body. fail_silently − Bool, if false send_mail will raise an exception in case of error. connection − E-mail backend. html_message − (new in Django 1.7) if present, the e-mail will be multipart/alternative. Sending HTML E-mail Sending HTML message in Django >= 1.7 is as easy as − from django.core.mail import send_mail from django.http import HttpResponse res = send_mail(“hello paul”, “comment tu vas?”, “[email protected]”, [“[email protected]”], html_message=”) This will produce a multipart/alternative e-mail. But for Django < 1.7 sending HTML messages is done via the django.core.mail.EmailMessage class then calling ”send” on the object − Let”s create a “sendHTMLEmail” view to send an HTML e-mail. from django.core.mail import EmailMessage from django.http import HttpResponse def sendHTMLEmail(request , emailto): html_content = “<strong>Comment tu vas?</strong>” email = EmailMessage(“my subject”, html_content, “[email protected]”, [emailto]) email.content_subtype = “html” res = email.send() return HttpResponse(”%s”%res) Parameters details for the EmailMessage class creation − Subject − E-mail subject. message − E-mail body in HTML. from_email − E-mail from. to − List of receivers’ e-mail address. bcc − List of “Bcc” receivers’ e-mail address. connection − E-mail backend. Let”s create a URL to access our view − from django.conf.urls import patterns, url urlpatterns = paterns(”myapp.views”, url(r”^htmlemail/(?P<emailto> [w.%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4})/”, ”sendHTMLEmail” , name = ”sendHTMLEmail”),) When accessing /myapp/htmlemail/[email protected], we get − Sending E-mail with Attachment This is done by using the ”attach” method on the EmailMessage object. A view to send an e-mail with attachment will be − from django.core.mail import EmailMessage from django.http import HttpResponse def sendEmailWithAttach(request, emailto): html_content = “Comment tu vas?” email = EmailMessage(“my subject”, html_content, “[email protected]”, emailto]) email.content_subtype = “html” fd = open(”manage.py”, ”r”) email.attach(”manage.py”, fd.read(), ”text/plain”) res = email.send() return HttpResponse(”%s”%res) Details on attach arguments − filename − The name of the file to attach. content − The content of the file to attach. mimetype − The attachment”s content mime type. Print Page Previous Next Advertisements ”;
Django – Add Master Template
Django – Add Master Template ”; Previous Next Django supports template inheritance. The concept of inheritance in Django is very similar to inheritance in object-oriented programming. The idea is that the output rendered by each view in a web application must follow a uniform pattern or look, even though each view may render a different template. Suppose a Django app has three URL routes registered with three views. We want to design the template in such a way that each view should have a page header, a footer and a sidebar with links and the variable content displayed to its right. The Master Template A base class in any object-oriented language (such as Python) defines attributes and methods and makes them available to the inherited class. In the same way, we need to design a master template that provides an overall skeleton for other templates. The master template (sometimes called “base template”), along with the common structure, also marks the dummy blocks. The child template inherits the common structure and overrides the blocks to provide respective contents. Such blocks are marked with “block – endblock” construct. {% block block_name %} … … {% endblock %} The master template may have more than one such blocks in different places. Each one should be provided a unique identifier. The HTML code for our master template (base.html) is as follows − <!doctype html> <html> <body> <!–header–> <div style=”height:10%;”> <h2 align=”center”>My Web Application</h2> <hr> </div> <div style=”width:100%;”> <!—side bar–> <div style=”width:20%; float:left; border-right-style:groove”> <ul> <b> <li><a href=””>home</a></li> <li><a href=”register/”>register</a></li> <li><a href=”login/”>login</a></li> </b> </ul> </div> <!–contents–> <div style=”margin-left:21%;”> <p> {% block contents %} {% endblock %} </p> </div> </div> <br><br><br> <!–footer–> <hr> <div> <h4 align=”right”>All rights reserved</h4> </div> </body> </html> The template for the home page (index.html) inherits this base.html by the tag − {% extends “base.html” %} It populates the dummy content block with its own content − <!doctype html> <html> <body> {% extends “base.html” %} {% block contents %} <h2 align=”center”>This is Home page</h2> {% endblock %} </body> </html> Define a View Let us define a view that renders this template − from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index(request): return render(request, “index.html”, {}) Register the View We also need to register this view in urls.py − urlpatterns = [ …, path(”home/”, views.index, name=”home”), ] When http://localhost:8000/myapp/home URL is opened, the home page template is rendered with the header, sidebar and footer as designed in base.html − Print Page Previous Next Advertisements ”;
Django – Creating Views
Django – Creating Views ”; Previous Next A view function, or “view” for short, is simply a Python function that takes a web request and returns a web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image, etc. Example: You use view to create web pages, note that you need to associate a view to a URL to see it as a web page. In Django, views have to be created in the app views.py file. Simple View We will create a simple view in myapp to say “welcome to my app!” See the following view − from django.http import HttpResponse def hello(request): text = “””<h1>welcome to my app !</h1>””” return HttpResponse(text) In this view, we use HttpResponse to render the HTML (as you have probably noticed we have the HTML hard coded in the view). To see this view as a page we just need to map it to a URL (this will be discussed in an upcoming chapter). We used HttpResponse to render the HTML in the view before. This is not the best way to render pages. Django supports the MVT pattern so to make the precedent view, Django – MVT like, we will need − A template: myapp/templates/hello.html And now our view will look like − from django.shortcuts import render def hello(request): return render(request, “myapp/template/hello.html”, {}) Views can also accept parameters − from django.http import HttpResponse def hello(request, number): text = “<h1>welcome to my app number %s!</h1>”% number return HttpResponse(text) When linked to a URL, the page will display the number passed as a parameter. Note that the parameters will be passed via the URL (discussed in the next chapter). Print Page Previous Next Advertisements ”;