About me

Wednesday, September 26, 2018

python django (django template language 2)

Django Template Language

Tags
for
The for loop over each item in an array for example to display a list of athletes provided in athlete_list:

<ul>
{%for athlete in athlete_list%}
<li>{{athlete.name}}</li>
{%endfor%}
</ul>
if ,elif,and else
Evaluates a variable and if that variable is true the contents of the block are displayed


{% if athlete_list %}
    Number of athletes: {{ athlete_list|length }}
{% elif athlete_in_locker_room_list %}
    Athletes should be out of the locker room soon!
{% else %}
    No athletes.
{% endif %}

in the above if athlete_list is not empty the number of athletes will be displayed by the {{athlete_list|length}} variable . Otherwise if athlete_in_locker_room_list is not empty the message "Athletes should be out..." will be displayed if both lists are empty "No athletes " will be displayed
you can also use filters and various operators in the if tag:
{% if athlete_list|length > 1 %}
   Team: {% for athlete in athlete_list %} ... {% endfor %}
{% else %}
   Athlete: {{ athlete_list.0.name }}
{% endif %}
most templates will return string so mathematical comparisons using filters will generally not work as you expect Length is an exception
Comments
the comment out part of a line in a template use the comment syntax{# #} for example this template would render as 'hello':
{#greeting#}hello
a comment can contain any template code invalid or not For example


{# {% if foo %}bar{% else %} #}

This syntax can only be used for single-line comments (no newlines are permitted between the {# and #} delimiters). If you need to comment out a multiline portion of the template, see the comment tag.
Template inheritance
The most powerful and thus the most complex - part of djangos template engine is template inheritance . template inheritance allow you to build a base skeleton template that contains all the common elements of your site and defines block that child templates can override

 Comments

 The method to comment out part of a line in a template we can use {# #}
by using this we can comment out for example

{#hello#}greetings
The template would render as 'greeting' a comment can contain any code invalid or not for example
{# {% if foo %}bar{% else %} #}
This syntax can only be used for single line comments (no newlines are permitted between the {#and#} delimiters  ) its used only for single line comments but to comment out multiline line comment we use {%comment%}and{%endcomment%} an optional note can be inserted in the first tag this is useful when commenting out code for documentint why the code was disabled .

<p>Rendered text with {{ pub_date|date:"c" }}</p>
{% comment "Optional note" %}
    <p>Commented out text with {{ create_date|date:"c" }}</p>
{% endcomment %}
comment tags cannot be nested

Template inheritance 

 as inheritance in other languages the template inheritance allows us to build a base skeleton template that contains all the common elements of our site and defines blocks that child templates can override
 its easiest to understand template inheritance y starting with an example

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css">
    <title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
    <div id="sidebar">
        {% block sidebar %}
        <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/blog/">Blog</a></li>
        </ul>
        {% endblock %}
    </div>

    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
this template will be our base class which is base.html its a simple html skeleton document that you might use for a simple two coloumn page its the job of child templates to fill the empty blocks with content
In this example the block tag defines three blocks that child templates can fill in all the block tag does is to tell the template engine that a child template may override those portions of the template
A child template might look like this :

{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}
{% for entry in blog_entries %}
    <br />
<h2>
{{ entry.title }}</h2>
{{ entry.body }}<br />
{% endfor %}
{% endblock %}


More on template inheritance and django template language will be included in next pages till then thanks for reading this blog and kindly expecting your feed backs please reply on comment section and follow let me know your suggestions and follow me and share this blog





Monday, September 3, 2018

python django (Django Template Language)


Django Template Language

The template language as we explained earlier here we are going to learn more about template language Django template system is not simply python embedded into html this is by design the template system is meant to express presentation not programe logic the django template system provides tags which function similarly to some programming constructs an if tag for boolean tests a for tag for looping etc but these are not simply executed as the corresponding python code and the template system will not execute arbitrary python expressions

Templates
A template is simply a text file it can generate any text base format (HTML,XML, CSV,etc)
which contains variables which get replaced with values when the template is evaluated and tags which control the logic of the template

Here is an example
{%extends "base_generic.html"%}
{%block title %}{{section .title}}{%endblock%}
{%block content%}
<h1>{{section.title}}</h1>
{%for story in story_list%}
<h2><a href="{{story.get_absolute_url}}">{{story.headline|upper}}</a></h2>
<p>{{story.tease|truncatewords:"100"}}</p>
{%endfor%}
{%endblock%}

Variables
Variables look like this {{variable}} when the template engine encounters a variable it evaluates that variable and replaces it with the result variable names consist of any combination of alphanumeric characters and the underscore ("_") but may not start with an underscore The dot (".") also appears in variable sections although that has a special meaning as indiacated below importantly but we cannot have spaces or punctuations characters in variable names the dot are used to access attributes of a variable the above example {{section.title}} will be replaced with the title attribute of the section object
If you use a variable that doesnt exist the template system will insert the value of the string_if_invalid option which is set to ' ' (the empty string) by default note that var in a template expression like {{foo.bar}} will be intterpreted as a literal string and not using the value of the variable bar if one exists in the tempate context

Filters

the filters are used to modify variables to display here is an example for filter like this
{{name|upper}} this displays the value of the{{name}} variable after being filtered through the upper filter which converts text to uppercase by using a pipe (|) to apply a filter filters can be chained
the output of one filter is applied to the next {{text|escape|linebreaks}} is a common idion for escaping text contents then converting line breaks to <p> tags

some filters take arguments a filter argument looks like this {{bio|truncatewords:30}} this will display the first 30 words of the bio variable
there are about sixty builtin template filters you can read that in this link  built-in filter reference
some most commonly used filters are following
default
if a variable is false or empty use given default otherwise use the value of the example:


{{value|default :"nothing"}}
if value is not provided or is empty the above will display nothing
length
returns the length of the value this works for both strings and lists for example:

{{value|length}}
if value is ['a','b','c','d'] the output will be 4
filesizeformat
formats the value like a human readable file size (i.e '13 KB' , '4.1 MB','102 bytes',etc ) for example


{{value|filesizeformat}}
if value is 123456789, the output would be 117.7 MB you can also build custom template tags which will be explained in other posts

Tags

Tags look like this : {% tag %} tags are more complex than variables some create text in the output some control flow by performing loops or logic and some load external information into the template to be used by later variables 
some tags require beginning and ending tags {% tag %} ....... tag contents.....{%endtag%} 
there are many template tags you can find it in the given link as built-in tag reference
there are some commonly used tags which will be explained on next post thanks for viewing my post



MY friends i kindly expect your feedback to improve my posts please share and follow my blog if any doubts please comment 



Sunday, June 24, 2018

python django Automatic Testing part 4

Know the testing output
The testing output of django here we will see that when we run our tests we will see number of test messages as the test runner prepares itself .Test runner is a component which orchestrates the execution of tests and provides the outcome to the user it may use a graphical interface a textual interface or return a special value to indicate the results of executing the tests
                    If you wish you can control the level of detail of these messages with the verbosity option on the command line like you can run tests with more detail (higher verbosity) by passing in the -v flag some of the other options are
-b,--buffer:
the standard output and standard error streams are buffered during the test run output during a passing test is discarded output is echoed normally on test fail or error and is added to the failure messages
-c,--catch:
     control c during the test run waits for the current test to end and then reports all the results so far A second control-c raises the normal KeyboardInterrupt exception
-f --failfast:
 stop the test run on the first error or failure
--locals:
   show local variables in tracebacks
and you can get all the command line options put -h as  
python -m unittest -h
here is an example of using -v

python -m unittest -v test_module
likewise we can use the options and after running the tests here
Creating test database...
Creating table myapp_database
Creating table myapp_mineral
This here tells you that the test runner is creating a test database as described in the previous posts once the database has been created Django will run your tests if every thing goes well we will see something like this as for example

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

Ran 22 tests in 0.221s

OK
otherwise we will get error like this
======================================================================
FAIL: test_was_published_recently_with_future_poll (polls.tests.PollMethodTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/dev/mysite/polls/tests.py", line 16, in test_was_published_recently_with_future_poll
    self.assertIs(future_poll.was_published_recently(), False)
AssertionError: True is not False

----------------------------------------------------------------------
Ran 1 test in 0.003s

FAILED (failures=1)

To learn more about python unittest you can go to this link one thing to note here the return code for the test runner script is 1 for any number of failed and erroneous test if all tests pass the return code is 0 this feature is useful if you're using the test runner script in a shell script and need to test for success or failure at that level


 Thats for this post guys more on testing will be on next post please comment share and follow this blog

Sunday, June 17, 2018

python django Automated testing part 3(please read my previous post ))

Finding data form production database when running tests
       if the code attempts to access the database when its modules are compiled this will occur before the test database is set up with potentially unexpected results For example if we have a database query in the module level code and a real database exists . then the production data could pollute the tests it is a bad idea to have such import time database queries in your code
so we should have to rewrite the code so that it doesn't do this. This also applies to customized implementation of ready()

Order of Test execution
Django test runner reorders tests as
  • All the TestCase subclasses are run first
  • Then all other Django-based tests (test case based on SimpleTestCase,including TransactionTestCase) are run with no particular ordering guaranteed nor enforced among them
  • then any other unittest.TestCase test (including doctests) which may alter the database without restoring it to its orginal state are run
Note:
     The new ordering of tests may reveal unexpected dependencies on test case ordering this is the case with doctests that relied on state left in the database by a given TransactionTestCase test they must be updated to be able to run independently

To ensure your tests are indepndent from each other you may reverse the execution order inside groups using the test --reverse option

Make initial data loaded Available(Rollback emulation)
        It is only be available in TestCase tests and not in TransactionTestCase tests and this also true for tests which rely on TransactionTestCase such as LiveServerTestCase and StaticLiveServerTestCase
and available to only on backends where transactions are supported the most important exception being MyISAM
By setting the serialized_rollback option to True in the body of the TestCase or TransactionTestCase django can reload that data for you on a per testcase basis but it will slow down that test suite by approximately 3x
We can exclude some apps from this process and speed up test runs slightly to this add those apps to TEST_NON_SERIALIZED_APPS to prevent serialized data from being loaded twice setting serialized_rollback = True disables the post_migrate signal when flushing the test database

Some Test conditions
   The value of  the DEBUG = False is set on all django tests run this is to ensure that the observed output of our code matches what will be seen in a production setting
Caches are not cleared after each test and running "manage.py test myapp" can insert data from test into the cache of a live system if you run your tests in production because unlike databases a separate "test cache" is not used This behavior may change in the future
Speeding up the tests
    By running tests in parallel as long as your tests are properly isolated it will run in parallel to gain speed up on multicore hardware. one thing to note here when test parallelization is enabled and a test fails django may be unable to display the exception traceback This can make debugging difficult if you encounter this problem run the affected test without parallelization to see the traceback of the failure
Password hashing
    default password hasher is slow by design if you are authenticating many users in your tests you may want to use a custom settings file and set the PASSWORD_HASHER setting to a faster hashing algorithm

PASSWORD_HASHERS = [
'django.contrib.auth.hashers.MD5PasswordHasher',
]

Also include PASSWORD_HASHERS any hashing algorithm used in fixtures If any

 Thats all for this post guys hope you understand and like this post to get latest updates on this lesson follow by email and don't forget to follow and share if you have any suggestions or doubts please include it in the comment section so that i can improve my next post

Friday, June 15, 2018

python django Automated testing part 2

Running Test

we have learned about tests in the previous lesson now here we can see how to run the test to run the test write this code in the commandline as


$/. manage.py test


The test are discovered with using the built in test discovery which by default in python which will discover any file named test.py under the current working directory we can also specify the specific that is required in by supplying any number of test labels to ./manage.py test which are a full python dotted path to a package, module, Test case subclasses or test methods like in here
# to run all the tests in the vehicles.tests module
$ ./manage.py test vehicles.tests

#to run all the tests in the vehicle package
$./manage.py test vehicles

# to run one test case
$./ manage.py test vehicles.tests.VehicleTestCase

#to run just one test method
$ ./manage.py test vehicles.tests.VehicleTestCase.test_vehicle_can_fly

#to provide a path to a directory to discover tests below that directory
$ ./manage.py test vehicles/

we can also specify a custom file name pattern using the -p (or --pattern) option if your test files are named differently from the test*.py pattern
$ ./manage.py test --pattern = *tests_*.py*
Test which requires databases ( namely model test) will not use the real production database they use a separate blank database are created for tests regardless of the tests pass or fail the test database are destroyed when all the tests have been executed you can prevent the database being destroyed using the test --keepdb option this will preserve the test database between runs if the database does not exist it will be created first any migrations will also be applied in order to keep it up to date
to complete the test currently running and exit gracefully we need to press Ctrl-c it will wait for the currently running test to complete and then exit gracefully and it will output the details of any test failures report on how many tests were run and how many errors and failures were encountered and destroy any test database as usual if you forget to pass --failfast option then you can use this Ctrl-c and if you don't want to wait for the current test to finish press Ctrl-c once more and the test run will halt immediately but not gracefully no details of the tests run before the interruption will be reported and any test databases created by the run will not be destroyed
we can use this flag --Wall which tell python to display deprecation warnings django like many other python libraries uses these warnings to flag when features are going away  it also might flag the codes which are not strictly wrong but could benefit from a better implementation


More on test database

The test database names are created by prepending test_ to the value of each NAME in DATABASES when using SQLite the tests will use an inmemory database by default the database will be created in memory ,bypassing the filesystem entirely The TEST dictionary in DATABASES offers a number of settings to configure your test database and if you want to use a different database name specify NAME in the TEST dictionary for any given database in DATABASES

On PostgreSQL USER will also need read access to the built in postgres database
and also test runner will use all of the same database settings which we have in our settings file:ENGINE, USER, HOST ,etc we need to make sure that the given user account has sufficient privileges to create a new database on the system due to the reason that the test database is created by the user specified by USER

For fine grained control over the character encoding of the test database use the CHARSET TEST option and COLLATION option for MySQL to control the particular collation used by the test database
And there is a facility using SQLite 3.7.13+ which is shared cache which is enabled so you can write tests with the ability to share the database between threads



Thats all for this post guys more will be included in the next post hope you like the post waiting for your suggestions to improve my posts so please comment , share and to get latest updates on this lessons follow by email and follow me 

Tuesday, June 12, 2018

python django Automated Testing

Automated Testing

The automated testing are simple routines that checks the operation of your code . There are some tests  which tests the small part of the code and others are which tests the overall operation of the program automated tests are tests which are done by the system for us like we create a set of tests and then we make changes to our app and test if the code works as if we it were originally intended to work without performing time consuming manual testing

Benefits of Testing

  • Test will save Time:If we change any of the components of the code could cause unexpected application behavior checking that it still works means running the test through your code functionality with twenty different variations of your test data just to make sure its working properly this is not a good use of time we can do this test in seconds with automated testing like writing the automated test is more beneficial than testing your application manually 
  •  Test prevent the problem: they can prevent the coming problems from identifying them early before you could fall in any problems
  • Test make the code more attractive: if you have made an amazing software then also most developers will refuse to take your software because it lacks tests they won't trust it jacob koplan moss one of the original developers of django says that code without test is broken by design the other developers want see test in your software to take it seriously 
  • Test helps teams work together: The tests helps in software which are made by teams test guarantees that the colleagues don't inadvertently break your code and you don't break their code without knowing 

The different Testing strategies

There are many ways to approach on writing test one of the discipline is the test driven development in which that relies on the repetition of a very short development cycle requirements are turned in to very specific test cases then the software is improved to pass the new tests only some programmers write their tests before their code test driven development simply formalizes the problem in a python test case it will be difficult to figure out where to get started with writing test if there are thousands of line of python code choosing something to test might not be easy its beneficial write the first test before you make a change either when you add a new feature or fix bugs

Start to write our first Test

The django unit test uses the python standard library module unittest
  this module defines test using a class based approach first in our code we make a subclass of  TestCase from django.test which is a subclass of unittest.TestCase that runs each test inside a transaction to provide isolation

from django.test import TestCase
from myapp.models import Animal
 
class AnimalTestCase (TestCase):
       def setup(self):
             Animal.objects.create(name= "lion" ,color = "brown")
             Animal.object .create(name = "tiger", color = "red")
       def animal_has_color(self):
             """Animals that have color are identified"""
           Lion = Animal.objects.get(name = "lion")
           Tiger = Animal.objects.get(name = "tiger")
           self.assertEqual(lion.color(),"the lion has color 'brown'")
           self.assertEqual(tiger.color(),"the tiger has color 'red'")
In here the test case when we run it the default behavior of the test utility is to find all the test cases that is subclasses of unittest.TestCase in any file whose name begins with test automatically build a test suite out of those test cases and run the test suit
As explained in my previous chapters by default the test.py file will be created in the new applicatiion of "myproj" folder but this will not be enough as your test suite grows at that time you will need to restructure it into a tests package so you can split your tests into different submodels such as test_models.py,test_views.py,test_forms.py etc you can pick whatever organizational scheme you like and one important point to note here is if your tests rely on database access such as creating or querying models be sure to create the test classes as subclasses of django.test.TestCase rather than unittest.TestCase because using unittest.TestCase avoids the cost of running each test in a transaction and flushing the database but if your tests interact with the database their behavior will vary based on the order that the test runner executes then this can lead to unit tests that pass when run in isolation but fails when run in a suite

More on how to run the tests and more will be included in the next post hope you like the post to get latest updates please follow by email and dont forget to share ,follow and comment below your doubts and suggestions



Sunday, May 20, 2018

python django chap 11

Friends this is the continuation from its previous post so i kindly recommend you to read that post i have made this very simple even a complete beginner can learn it and if you are beginner in python then you need to learn python i have made that blog also for that click this link

HANDLING UPLOADED files

In the previous post we have learn to bind the request.FILES into the forms constructor now here we will learn common methods to handle the uploaded file as for example an uploaded file can be
def handle_uploaded(f) :
           with open ('some/file/name.txt','wb+') as destination :
           for chunk in f.chunks():
                      destination.write(chunk)
           
Looping over UploadedFile.chunks() instead of using read() ensure that large file don't overwhelm your systems memory

HANDLING UPLOADED FILE WITH MODEL
If you are saving file on a Model with a FileField using a ModelForm the file object will be saved to the location specified by the upload_to argument of the corresponding FileField when calling form.save
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import ModelFormWithFileField
          def upload_file (request):
                    if request.method==POST:
                             form = ModelFormWithFileField(request.POST,request.FILES)
                              if form.is_valid():
                                        form.save
                                         return HttpResponseRedirect('/success/url/')
                     else:
                            form = ModelFormWithFileField()
                   return render (request,'upload.html',{'form':form})
If you are constructing an object manually you can simply assign the file object from request.FILES to the file field in the model


from django.http import HttpResponseRedirect
from django.shortcuts import render
from .form import UploadFileForm
from .model import ModelWithFileField
            def upload_file(request):
                     if  request.method == POST:
                          form = UploadFileForm (request.POST,request.FILES)
                           if form.is_valid():
                                    instance = ModelWithFileField(file_field= request.FILES['file'])
                                    instance.save()
                                    return HttpResponseRedirect('/success/url/')
            else:
                   form = UploadFileForm()
                    return render (request ,'upload.html',{'form':form})


Uploading Multiple Files

                   the multiple files can be uploaded with the one form field . Set the multiple HTML attribute of the fields Widget
 
from django import forms class FileFieldForm(form.Form): file_field = forms.FileField (widget = forms.ClearableFileInput(attrs{'multiple':True}))
Then override the post method of the FormView subclass to handle the multiple file uploads
from django.views.generics.edit import FormView
from .forms import FileFieldForm
class FileFieldView(FormView):
      form_class = FileFieldForm()
       template_name = 'upload.html' #you can replace with your template
       success_url = '...' #replace with your url or reverse()
def post(self,request,*args,**kwargs):
                 form_class = self.get_form_class()
                 form = self.get_form(form_class)
                  files = request.FILES.getList('file_field')
            if form.is_valid():
                  for f in files
                        .....#do something with each file
      return self.form_valid (form)
 else:
      return self.form_invalid(form)  

That's all for this post guys now you have the basic knowledge to start learning the advanced lessons on django more advanced lessons will be included in future posts

THANKS FOR VIEWING MY BLOG HOPE YOU LIKE THE POST IF YOU WANT TO GET LATEST POSTS ON THIS PLEASE FOLLOW BY EMAIL ID AND FEEL FREE TO ASK YOUR DOUBTS AND DON'T FORGET TO SHARE,COMMENT AND FOLLOW

python django chap 10

Friends this is the continuation from its previous post so i kindly recommend you to read that post i have made this very simple even a complete beginner can learn it and if you are beginner in python then you need to learn python i have made that blog also for that click this link


GENERIC VIEWS

The generic views are used when in our earlier we created our views with functions such as index we can use and make more functions in the views for getting data from the database according to a parameter passed in the URL, loading a template and returning the rendered template.so django provides a simple method which is called as generic views. Generic views are classes and not  functions Generic views abstract common patterns to the point where you don’t even need to write Python code to write an app.and also to use that we need to change the URLconf were it is like the change in myproj/urls.py
path('', views.IndexView.as_view(), name='index')
and then we need to create our class in the myproj/views.py as we have removed the old index function and placed it with the IndexView as a class



from django.views.generic import TemplateView
 
class IndexView(TemplateView):
                 template_name = 'myproj/index.html'
            
This will display the template view there are different types of generic views as given here is the TemplateView which renders the template, with the context containing parameters captured in the URL.And other type of generic view is as the DetailView and ListView which will do as display a detail page for a particular type of object and other one will display a list of objects for more details on generic views click this  link

Uploading files 

                
when django handles file uploads it ends up in the placed in request.FILES. At first here we will consider a simple form containing a file upload field so for that we need to upload file there in forms.py file write as
from django import forms
class UploadFileForm(forms.Form):
        title = forms.CharField(max_length=50)
        file = forms.FileField()
The view handling this will receive the data in request.FILES which is a dictionary containing a key for each FileField(ImageField or any other FileField subclasses). in the form the data from the above form can be accessed as request.FILES ['file'].in order to upload files, it is to be submitted using the post method and also you need to make sure that your <form> element correctly defines the enctype as "multipart/form-data"

<form enctype="multipart/form-data" method="post" action="/foo/">

django have model fields to upload the files like FileField  and ImageField the files uploaded here are not stored in database but in the filesystem it is stored .they are created as a string field in the database  usually as VARCHAR which is the reference to the actual file if we delete one file it will not delete the physical file but only the reference to the file.      
                                             
                                         Now we will see the methods to file upload in here as normal you will pass your file as simple from request in to the form by binding the file with the forms .As is the case of forms which deals with FileField and ImageField are little more complicated than the normal ones here we need to specify a second argument when we bind our form. as for example if included our form with an ImageField called as image we need to bind the file data containing the image data in here given an example for it :


from django.core.files.uploadfiles import SimpleUploadFile
data = { 'subject' = 'this is the subject'
              'message'= 'this is the messge'
              'sender' = 'this@this.com'
              'cc_myself' = True }
file_data = {'image':SimpleUploadFile (img.jpg),<file data>}
f = ContactFormWithImage(data,file_data)

we will usually specify request.FILES as the source of the file data As above we can make a bound form like
f = ContactFormWithImage(request.POST,request.FILES)
here is a form with unbound
f = ContactFormWithImage{}
We can create the views like
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadFileForm
 #and an imaginary function to handle uploaded file
from somewere import handle_uploaded
def upload_file(request):
       if request.method== POST:
           form = UploadFileForm(request.POST,request.FILES)
            if form.is_valid():
                  handle_uploaded(request.FILES['file'])
                  returnHttpResponseRedirect('success/url/')   
else :
           form = UploadFileForm()
           return = render (request,'upload.html',{'form':form})
More on this topic will be included in the next post

THANKS FOR VIEWING MY BLOG HOPE YOU LIKE THE POST IF YOU WANT TO GET LATEST POSTS ON THIS PLEASE FOLLOW BY EMAIL ID AND FEEL FREE TO ASK YOUR DOUBTS AND DON'T FORGET TO SHARE,COMMENT AND FOLLOW

Friday, May 18, 2018

python django chap 9

Friends this is the continuation from its previous post so i kindly recommend you to read that post i have made this very simple even a complete beginner can learn it and if you are beginner in python then you need to learn python i have made that blog also for that click this link

                                      PAGE REDIRECTIONS

The redirection is necessary when you need your user to go to a different page when the desired direction is on error or due to some other reasons In Django, redirection is accomplished using the 'redirect' method.
                            The 'redirect' method takes as argument: The URL you want to be redirected to as string A view's name
The myproj/views looks like the following so far −

from django.shortcuts import render, redirect
from django.http import HttpResponse
import datetime

# Create your views here.
def index(request):
    today = datetime.datetime.now().date()
    return redirect("https://www.djangoproject.com")
  def  myno(request, myno):
   """ A view that display a name based on his ID"""
   text = "Displaying Number : %s" %myno
   return redirect(mynumbers, year = "2045", month = "02")
 
def mynumbers(request, year, month):
   text = "Displaying numbers of : %s/%s"%(year, month)
   return HttpResponse(text)
 


Here we have changed our view to redirect our index view to the django official site by adding the complete url of the site in the redirect method in the index view  and the myno view is redirected to the mynumbers view here by giving its name as parameter here
It is also possible to specify whether the 'redirect' is temporary or permanent by adding permanent = True parameter. The user will see no difference, but these are details that search engines take into account when ranking of your website.


SENDING E-MAIL


The django use the help of  import django.core.mail. as of like in python it is import of smtplib to start sending email we need to edit our settings .py file and set the following options which is


  • EMAIL-HOST − smtp server host
  • EMAIL_HOST_USER − Login credential for the smtp server.
  • EMAIL_HOST_PASSWORDPassword credential for the smtp server.
  • EMAIL_PORTsmtp server port.
  • EMAIL_USE_TLS or _SSLTrue if secure connection
now we will create a simple e-mail to send as

from django.core.mail import send_mail
from django.http import HttpResponse
def sendSimpleEmail(request,emailto):
    
res = send_mail('Subject here','Here is the message.','from@example.com',['to@example.com'],fail_silently=False,)
       return HttpResponse('%s'%res)


here the send_mail has the things which a email is composed of like the parameters first which is subject of the mail which will be a string then comes the main content or the message which is to be sent of the mail which will be a string then the from address or the mail id of the sender it is also a string and the mail id of the receiver A list of strings, each an email address. Each member of recipient_list will see the other recipients in the “To:” field of the email message. then comes the fail_silently which comes Bool, if false send_mail will raise an exception in case of error.The character set of email sent with django.core.mail will be set to the value of your DEFAULT_CHARSET setting.
The other parameters used in here are
  • 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.
The return value will be the number of successfully delivered messages (which can be 0 or 1 since it can only send one message).

Sending Multiple Mails with send_mass_mail()

The send_mass_mail is intended to handle mass mailing were it have an extra parameter different to send_mail is a datatuple for example

send_mass_mail(datatuple, fail_silently=False, auth_user=None, auth_password=None, connection=None)

fail_silently ,auth_user,auth_password,has the same function as in the send_mail() and the datatuple is a tuple with each element is in a format

(subject, message, from_email, recipient_list)
The connection in here is a email backend Each element of datatuple results in a separate email message. As in send_mail(), recipients in the same recipient_list will all see the other addresses in the email messages’ “To:” field.
from django.core.mail import send_mass_mail
from django.http import HttpResponse
 def sendMassEmail(request,emailto):
     msg1 = ('subject 1', 'message 1', 'nads@sani.com', [recipient1])
     msg2 = ('subject 2', 'message 2', 'nads@sani.com', [recipient2])
     res = send_mass_mail((msg1, msg2), fail_silently = False)
     return HttpResponse('%s'%res)
Here we have send the messages and the return value will be the number of successfully delivered messages the main difference between send_mail and send_mass_mail is that the send_mail opens a connection to the mail server each time its executed and the send_mass_mail uses a single connection for all of its messages this confirms that the send_mass_mail() is slightly more efficient

Sending mail to admins

Sending mails to admin is done by the shortcut django.core.mail.mail_admins as defined in the ADMINS settings mail_admins prefixes the value of the EMAIL_SUBJECT_PREFIX setting which is[Django] by default the from header of the email will be the value of SERVER_EMAIL setting this method exists for convenience and readability If html_message is provided, the resulting email will be a multipart/alternative email with message as the text/plain content type and html_message as the text/html content type. an example for sending mail to admin is as 

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)
It will send the mail to the admin mail id as defined in the ADMIN settings

SENDING MAIL TO MANAGERS

the method of sending mail to managers is also similar to sending mail to admins for example here it is as
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)
as explained earlier it is as similar to sending mail to admins in here it is sending it to managers 
that's all for this post friends learn more from the next post. 


THANKS FOR VIEWING MY BLOG HOPE YOU LIKE THE POST IF YOU WANT TO GET LATEST POSTS ON THIS PLEASE FOLLOW BY EMAIL ID AND FEEL FREE TO ASK YOUR DOUBTS AND DON'T FORGET TO SHARE,COMMENT AND FOLLOW

python django chap 8

Friends this is the continuation from its previous post so i kindly recommend you to read that post i have made this very simple even a complete beginner can learn it and if you are beginner in python then you need to learn python i have made that blog also for that click this link


CREATING FORMS

A form is a collection of elements inside<form>...</form> that allow a visitor to do things like enter text, select options, manipulate objects or controls, and so on, and then send that information back to the server.


Some of these form interface elements - text input or checkboxes - are fairly simple and are built into HTML itself. Others are much more complex; an interface that pops up a date picker or allows you to move a slider or manipulate controls will typically use JavaScript and CSS as well as HTML form <input /> elements to achieve these effects.you can learn more on forms in the link here
Django handles three distinct parts of works involves in the form
  • preparing and restructuring data to make it ready for rendering
  •  creating HTML forms for the data
  •  receiving and processing submitted forms and data from the client
The main benefit of django is that Django can take care of it all for you.if you want you can code it all manually
the django has a form class .It is much as the same way that a Django model describes the logical structure of an object, its behavior, and the way its parts are represented to us, a Form class describes a form and determines how it works and appears.
In a similar way that a model class’s fields map to database fields, a form class’s fields map to HTML form  <input /> elements. (A ModelForm maps a model class’s fields to HTML form  <input/>elements via a Form; this is what the Django admin is based upon.) A form’s fields are themselves classes; they manage form data and perform validation when a form is submitted. A DateField and a FileField handle very different kinds of data and have to do different things with it. A form field is represented to a user in the browser as an HTML “widget” - a piece of user interface machinery. Each field type has an appropriate default Widget class, but these can be overridden as required.

<form action="/your-name/" method="post">
    <label for="your_name">Your name: </label>
    <input id="your_name" type="text" name="your_name" value="{{ current_name }}">
    <input type="submit" value="OK">
</form>


This tells the browser to return the form data to the URL /your-name/, using the POST method. It will display a text field, labeled “Your name:”, and a button marked “OK”. If the template context contains a current_name variable, that will be used to pre-fill the your_name field.
now we need to build a view which renders the template containing the HTML form, and that can supply the current_name field as appropriate and when the form is submitted the post request contains the form data to be submitted now we will create our form in the myproj/form.py it is as

from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=100)

this defines a form class with single field your_name.with label is also given if  which will appear in the <label> when its rendered .The fields maximum allowable length is is defined in the max_length and the The whole form, when rendered for the first time, will look like:

<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" maxlength="100" required />

Form data sent back to a Django website is processed by a view, generally the same view which published the form. This allows us to reuse some of the same logic.to handle it we need to instantiate it in the view for the URL where we want it to be published .

from django.http import HttpResponseRedirect
from django.shortcuts import render

from .forms import NameForm

def get_name(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect('/thanks/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = NameForm()

    return render(request, 'name.html', {'form': form})
if we arrive at this view with a get request it will create an empty form instance and place it in the template context to be rendered. This is what we can expect to happen the first time we visit the URL

If the form is submitted using a POST request, the view will once again create a form instance and populate it with data from the request: form = NameForm(request.POST) This is called “binding data to the form” (it is now a bound form). .
A Form instance has an is_valid() method, which runs validation routines for all its fields. When this method is called, if all fields contain valid data, it will return true and place in its cleaned_data attribute we can use this data to update the database or do other processing before sending an HTTP redirect to the browser telling it where to go next. if its not true we will go back to the template with the form This time the form is no longer empty (unbound) so the HTML form will be populated with the data previously submitted, where it can be edited and corrected as required.
now we can create our html template which is as :

<form action="/your-name/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>

As we learned earlier all the form fields will be unpacked in the html template in the{{form}} with the feature of Django Template Language 
thats all for creating forms in django 


to be continued in the next post.....................

THANKS FOR VIEWING MY BLOG HOPE YOU LIKE THE POST IF YOU WANT TO GET LATEST POSTS ON THIS PLEASE FOLLOW BY EMAIL ID AND FEEL FREE TO ASK YOUR DOUBTS AND DON'T FORGET TO SHARE,COMMENT AND FOLLOW 

Wednesday, May 16, 2018

Python django chap 7 (Templates)

Friends this is the continuation from its previous post so i kindly recommend you to read that post i have made this very simple even a complete beginner can learn it and if you are beginner in python then you need to learn python i have made that blog also for that click this link



TEMPLATE NAMESPACING
Now we might be able to get away with putting our templates directly in myproj/templates (rather than creating another myproj subdirectory), but it would actually be a bad idea. Django will choose the first template it finds whose name matches, and if you had a template with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the easiest way to ensure this is by namespacing them. That is, by putting those templates inside another directory named for the application itself.

TEMPLATES 

Lets start with template as myproj/index.html

<html>
   <body>
 
      Hello World!!!Today is {{today}}<br />

      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>
Just like in Python you can use if, else and elif in your template 

Render Function

This is the method by how the template is used in the view The Render function takes three parameters which are
Request :The initial request.
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.

fill a context and return an HttpResponse object with the result of the rendered template. Django provides a shortcut.


from django.shortcuts import render


 
def index(request):
    today = datetime.datetime.now().date()
    
    return render(request, 'myproj/index.html',{ "today",today })


The code given above for the views will give the date to the template view and the template view will get the day from the date and display the result according to the day


BLOCK AND EXTEND TAGS
Here we are going to see about the template ingeritance the method in which the 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 index.html template to inherit from a alter_template.html.

<html>
   <head>
     
      <title>
         {% block title %}Page Title{% endblock %}
      </title>
     
   </head>
   
   <body>
  
      {% block content %}
         Body content
      {% endblock %}
     
   </body>
</html>
And now this is our myproj/index.html

{% extends "alter_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 alter_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 index.html we use extends to inherit from the alter_template.html then we fill the block define above (content and title).


Namespacing URL names


 The tutorial project has just one app, myproj. In real Django projects, there might be five, ten, twenty apps or more.  Django for differentiating the URL names between them add namespaces to your URLconf. In the myproj/urls.py file, go ahead and add an app_name to set the application namespace
app_name = 'myproj'
Hope you understand the part the rest is on the next post


THANKS FOR VIEWING MY BLOG HOPE YOU LIKE THE POST IF YOU WANT TO GET LATEST POSTS ON THIS PLEASE FOLLOW BY EMAIL ID AND FEEL FREE TO ASK YOUR DOUBTS AND DON'T FORGET TO SHARE,COMMENT AND FOLLOW  

Tuesday, May 15, 2018

Python django chap 6 (CREATING VIEWS)

Friends this is the continuation from its previous post so i kindly recommend you to read that post i have made this very simple even a complete beginner can learn it and if you are beginner in python then you need to learn python i have made that blog also for that click this link


CREATING VIEWS 

                 The views in django is simple python function that takes a web request and give a web response which can be a html content of the web page or a 404 error, or an XML document, or an image, etc. it is a type of web page that serves a specific function and has a specific template like in this blog it has different views like 

  •   Blog homepage – displays the latest few entries. 

  •   Entry “detail” page – permalink page for a single entry. 

  •   Year-based archive page – displays all months with entries in the given year.

  •   Month-based archive page – displays all days with entries in the given month.

  •   Day-based archive page – displays all entries in the given day. 

  •   Comment action – handles posting comments to a given entry.

Django will choose a view by examining the URL that’s requested (to be precise, the part of the URL after the domain name). You should remember that  To get from a URL to a view, Django uses what are known as ‘URLconfs’. A URLconf maps URL patterns to views in our myproj/views.py. to get more info on this you can go to URL dispatcher
Now we will create a simple view

 from django.http import HttpResponse

def hello(request):
   text = """<h1>welcome to my app !</h1>"""
   return HttpResponse(text)</div>
In here we have used the httpresponse to render the html code. To see this view as a page we need to map it to the url

Now to map it we will do as our myproj/url.py add this code


from django.conf.urls import patterns, include, url
 urlpatterns = patterns('',
 url(r'^hello/', 'myapp.views.hello', name = 'hello'),
 
 )

The marked line maps the URL "/home" to the hello view created in myapp/view.py file.mapping is composed of three elements
  • The pattern − A regexp matching the URL you want to be resolved and map. Everything that can work with the python 're' module is eligible for the pattern (useful when you want to pass parameters via url).
  • The python path to the view − Same as when you are importing a module
  • The name − In order to perform URL reversing, you’ll need to use named URL patterns as done in the examples above. Once done, just start the server to access your view via :http://127.0.0.1/hello
Each views is responsible for doing one of two things like returning the httpresponse object containing the content for the requested page, or raising an exception such as Http404. The rest is up to us.Your view can read records from a database, or not. It can use a template system such as Django’s – or a third-party Python template system – or not. It can generate a PDF file, output XML, create a ZIP file on the fly, anything you want, using whatever Python libraries you want.

TEMPLATES


 Template convenient way to generate HTML dynamically A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted..Django uses templates to make 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.Django ships built-in backends for its own template system, creatively called the Django template language (DTL)  The page’s design is hard-coded in the view. If you want to change the way the page looks, you’ll have to edit this Python code. So let’s use Django’s template system to separate the design from Python by creating a template that the view can use. for that we need to create a directory called template in our myproj directory Your project’s TEMPLATES setting describes how Django will load and render templates. The default settings file configures a DjangoTemplates backend whose APP_DIRS option is set to True. By convention DjangoTemplates looks for a “templates” subdirectory in each of the INSTALLED_APPS. Within the templates directory you have just created, create another directory called myproj, and within that create a file called index.html. In other words, your template should be at myproj/templates/myproj/index.html. Because of how the app_directories template loader works as described above, you can refer to this template within Django simply as myproj/index.html.
more on templates will be include in the next post
THANKS FOR VIEWING MY BLOG HOPE YOU LIKE THE POST IF YOU WANT TO GET LATEST POSTS ON THIS PLEASE FOLLOW BY EMAIL ID AND FEEL FREE TO ASK YOUR DOUBTS AND DON'T FORGET TO SHARE,COMMENT AND FOLLOW 

Monday, May 14, 2018

python dajango chap 5 (Admin Interface)

Friends this is the continuation from its previous post so i kindly recommend you to read that post i have made this very simple even a complete beginner can learn it and if you are beginner in python then you need to learn python i have made that blog also for that click this link

                            

                             Admin InterFace

FirstofAll to understand this chapter you have view the previous chapters from the older post so i kindly request you to view the older posts .The django admin interface is activated by default then we have to start the development server you need to make sure some modules are imported in the INSTALLED_APPS and MIDDLEWARE_CLASSES tuples of the pysite/settings.py file. for INSTALLED_APPS:
 
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
'django.contrib.staticfiles',
 'myproj', )
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',
)
In the previous chapters we have initiated the database if you have not initiated the database write the code as Before launching your server, to access your Admin Interface, you need to initiate the database
$ python manage.py migrate
If you don't have a superuser you will prompted to create a super user by this code you can create a super user
$ python manage.py createsuperuser
Then enter your desired username and press enter
Username: admin
you will then will be prompted to your desired email address
Email address: admin@example.com
The final step is to enter your password. You will be asked to enter your password twice, the second time as a confirmation of the first.
Password: **********
Password (again): *********
Superuser created successfully.
Now to start the Admin Interface, we need to make sure we have configured a URL for our admin interface. Open the pysite/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'^$', 'pysite.views.home', name = 'home'),
 # url(r'^blog/', include('blog.urls')),
 url(r'^admin/', include(admin.site.urls)), )

START THE DEVELOPMENT SERVER
Start the development server and explore it. If the server is not running start it like so:
$ python manage.py runserver
Now go to this url on your browser "http://127.0.0.1:8000/admin/" and you will see the login screen of the django admin

now try to login with the superuser account you created earlier
You should see a few types of editable content: groups and users. They are provided by django.contrib.auth, the authentication framework shipped by Django.and all registered models in your app you can administrate all of them. The interface gives you the ability to do at least the "CRUD" (Create, Read, Update, Delete) operations on your models.
Earlier we have created our models now we didn't see it here for that we need to add some code on the myproj.py/admin.py like so
from django.contrib import admin
from .models import Mytable
admin.site.register(Mytable)
Now that we’ve registered Mytable, Django knows that it should be displayed on the admin index page: there will be the mytable under the myproj created for you
if you click the mytable you will be directed to the table were you can edit the previously created table with website , mail ,name and phone number given
THE MAIN POINTS TO NOTE HERE ARE
  
  • The form is automatically generated from the Question model. 
  •  The different model field types (IntegerField, CharField) correspond to the appropriate HTML input widget. Each type of field knows how to display itself in the Django admin. 
The bottom part of the page gives you a couple of options:
             
  • Save – Saves changes and returns to the change-list page for this type of object.
  • Save and continue editing – Saves changes and reloads the admin page for this object. 
  • Save and add another – Saves changes and loads a new, blank form for this type of object.
  • Delete – Displays a delete confirmation page
Friends after you have familiarized with the models API and the admin site,continue to my next post 


THANKS FOR VIEWING MY BLOG HOPE YOU LIKE THE POST IF YOU WANT TO GET LATEST POSTS ON THIS PLEASE LEAVE YOUR EMAIL ID AND FEEL FREE TO ASK YOUR DOUBTS AND DON'T FORGET TO SHARE AND COMMENT ON MY BLOG