About me

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


Python django chap 4 (Working With API for CRUD operations)

                                    

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

                 

 

                  WORKING WITH API for CRUD operations


  First you go into the interactive Python shell and play around with the free API Django gives you. To invoke the Python shell, use this command:

$ python manage.py shell
We’re using this instead of simply typing “python”, because manage.py sets the DJANGO_SETTINGS_MODULE environment variable, which gives Django the Python import path to your pysite/settings.py file.
           
Let's create a "crudops" view to see how we can do CRUD operations(CREATE,READ,UPDATE AND DELETE) on models. Our myproj/views.py will then look like −
from myapp.models import Dreamreal
from django.http import HttpResponse

def crudops(request):
   #Creating an entry
   
   mytable = Mytable(
      website = "www.nads.com", mail = "nads@sani.com", 
      name = "nadssani", phonenumber = "8075467438"
   )
   
   mytable.save()
   
   #Read ALL entries
   objects = Mytable.objects.all()
   res ='Printing all Mytable entries in the DB : <br>'
   
   for elt in objects:
      res += elt.name+"<br>"
   
   #Read a specific entry:
   nadssani = Mytable.objects.get(name = "nadssani")
   res += 'Printing One entry <br>'
   res += nadssani.name
   
   #Delete an entry
   res += '<br> Deleting an entry <br>'
   nadssani.delete()
   
   #Update
   mytable = Mytable(
      website = "www.nads.com", mail = "nads@sani.com", 
      name = "nadssani", phonenumber = "8075467438"
   )
   
   mytable.save()
   res += 'Updating entry<br>'
   
   mytable = Dreamreal.objects.get(name = 'nadssani')
   mytable.name = 'rawther'
   mytable.save()
   
   return HttpResponse(res)
 
 
 
 
Now i will explain each of the process here To represent database-table data in Python objects, Django uses an intuitive system: A model class represents a database table, and an instance of that class represents a particular record in the database table. To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database.
After to read all the entries we have made we first select all then we print each of them in second line and then now we need to select the specific entry from the table for that we select with the get (name = nadssani) statement . and to delete the value we simply delete using the "nadssani.delete()".
and at last update the value also is done.


The save method have no return value

To create and save an object in a single step use create() method

Other Queryset Methods

we can also retrieve specific objects with filter() method if you need to select only a subset of the complete set of objects.to refine we use the initial query set  like that we obtained earlier
"filter(**kwargs)" method Returns a new QuerySet containing objects that match the given lookup parameters and "exclude(**kwargs)" method returns a new QuerySet containing objects that doesn't matches the given lookup parameters
Here we are giving a different example from earlier to get a lookup of  QuerySet of blog entries from the year 2018  use filter on the here with the Entry class objects

Entry.objects.filter(pub_date_year = 2018)
With the default class it is same as the 

Entry.objects.all().filter(pub_date__year=2018)
Most of the time we use methods like all(),get(),filter()and exclude() when you need to lookup objects from the database to get all the queryset methods click here

Linking Models

The other part to learn is the Linking of Models The 3 ways are many to one ,many to many , one to one
Many to one
       
To define a many-to-one relationship, use django .db. models .ForeignKey You use it just like any other Field type: by including it as a class attribute of your model. This ForeignKey () method needs a positional arguments which is the class to which it is related for example if software has a relation with a software company like company makes different softwares but the company is one softwares are many like for example :

from django.db import models
 class Company(models.Model):
     # ...
     pass
 class Software(models.Model):
     company = models.ForeignKey(Company, on_delete=models.CASCADE)
      # ...

Many to many relationship

To define many to many relationship , use ManyToManyField. use it just like any other Field type: by including it as a class attribute of your model. ManyToManyField requires a positional argument: the class to which the model is related.for example here if a building has many floors that means every floors can be on multiple buildings and each buildings will have multiple floors :

from from django.db import models
   class Floors(models.Model):
      # ...
      pass
  class Buildings(models.Model):
       # ...
      floors = models.ManyToManyField(Floors)

One to one relationship

To define a one-to-one relationship, use OneToOneField. You use it just like any other Field type: by including it as a class attribute of your model.OneToOneField requires a positional argument .the class to which the model is related for example if you were building a database of “places”, you would build pretty standard stuff such as address, phone number, etc. in the database. Then, if you wanted to build a database of restaurants on top of the places, instead of repeating yourself and replicating those fields in the Restaurant model, you could make Restaurant have a OneToOneField to Place (because a restaurant “is a” place; in fact, to handle this you’d typically use inheritance, which involves an implicit one-to-one relation). 


THANKS FOR VIEWING MY BLOG HOPE YOU LIKE THE POST IF ANY DOUBTS FEEL FREE TO ASK AND IF YOU WANT TO GET THE LATEST CHAPTERS AND UPDATES ON THIS BLOG PLEASE FOLLOW WITH YOUR E-MAIL ID AND DON'T FORGET TO SHARE AND COMMENT THIS POST

Saturday, May 12, 2018

Learn Python Django chap 3 (Creating Models)


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

                          

 

                                     MODELS

                 The Models is the single, definitive source of truth about your data contains the essential fields and behaviors of the data you’re storing. The goal is to define your data model in one place and automatically derive things from it. simply models is a class that represents table or collection in our DB, and where every attribute of the class is a field of the table or collection. Models are defined in the app/models.py (in our example: myproj/models.py)
                 
                                    here is an example of a model creation


from django.db import models
class Mytable(models.Model):

   website = models.CharField(max_length = 50)
   mail = models.CharField(max_length = 50)
   name = models.CharField(max_length = 50)
   phonenumber = models.IntegerField()
 class Meta:
      db_table = "dreamreal"
Each model is represented by a class that subclasses django.db.models.Model. Each model has a number of class variables, each of which represents a database field in the model.if you don't know python it will be beneficial to learn it from here. Each field is represented by an instance of a Field class – e.g., CharField for character fields and IntegerField for integers. This tells Django what type of data each field holds.The name of each Field instance (e.g. website or mail) is the field’s name, in machine-friendly format. You’ll use this value in your Python code, and your database will use it as the column name.Some Field classes have required arguments. CharField, for example, requires that you give it a max_length. That’s used not only in the database schema, but in validation, as we’ll soon see.Django supports all the common database relationships: many-to-one, many-to-many, and one-to-one.

ACTIVATING MODELS
The small bit of model code gives Django a lot of information. With it, Django is able to create database and schema (CREATE TABLE statements) for this app.Create a Python database-access API for accessing the Mytable objects.And don't forget that we need to tell our project that the "myapp" app is installed.for that we need to add the To include the app in our project, we need to add a reference to its configuration class in the INSTALLED_APPS setting.  To do so, update INSTALLED_APPS tuple in the settings.py file of your project (add your app name). after that the tuple will look like :


INSTALLED_APPS = (
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
'django.contrib.staticfiles',
 'myproj',
 )
i have already mentioned this before now django knows to inclulde your app in here it is "myproj"
now lets run another ccommand
$ python manage.py makemigrations myproj
You will see something similar to the following:
Migrations for 'myproj':
 myproj/migrations/0001_initial.py:
 - Create model Mytable
by doing this you are telling django that you are changing/creating new one and that you’d like the changes to be stored as a migration
Migrations are how Django stores changes to your models (and thus your database schema) - they’re just files on disk. You can read the migration for your new model if you like; it’s the file myproj/migrations/0001_initial.py. There’s a command that will run the migrations for you and manage your database schema automatically - that’s called migrate, and type the command 
$ python manage.py migrate
for more details on this click here
And exactly you should remember this three steps :
  •  Change your models (in models.py).
  •  Run python manage.py makemigrations to create migrations for those changes
  •  Run python manage.py migrate to apply those changes to the database.
The separate commands  in making and applying migrations in here is because you’ll commit migrations to your version control system and ship them with your app; they not only make your development easier, they’re also useable by other developers and in production.
To know more about manage.py click here

 

 

THANKS FOR VIEWING MY BLOG NEXT POST IS ON "WORKING WITH API" HOPE YOU LIKE THIS BLOG PLEASE COMMENT YOUR SUGGESTIONS AND SHARE THIS BLOG TO YOUR FRIENDS AND DON'T FORGET TO FOLLOW THIS BLOG

learn python django chap 2(Database Setup)

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

                               Database Setup

                   It is a python django project which is the continuation from the first part which is given on the sidebar please view that so you can understand this post after that open up mysite/settings.py. It’s a normal Python module with module-level variables representing Django settings. 


DEBUG = True


                                        There is an option as above This option lets you set if your project is in debug mode or not. Debug mode lets you get more information about your project's error. Never set it to ‘True’ for a live project. However, this has to be set to ‘True’ if you want the Django light server to serve static files. Do it only in the development mode.
                     
             
DATABASES = {
   'default': {
      'ENGINE': 'django.db.backends.sqlite3',
      'NAME': 'database.sql',
      'USER': '',
      'PASSWORD': '',
      'HOST': '',
      'PORT': '',
   }
 
              By default it uses SQLite. SQLite is included in Python, so you won’t
need to install anything else to support your database. but if you wish you can 
change the database as you wish like postgresql and  f you wish to use another 
database, install the appropriate database binding and change the following keys in the
DATABASES 'default' item to match your database connection settings
 
             
  • ENGINE – Either 'django.db.backends.sqlite3', 'django.db.backends.postgresql', 'django.db.backends.mysql', or 'django.db.backends.oracle'.
  • NAME – The name of your database. If you’re using SQLite, the database will be a file on your computer; in that case, NAME should be the full absolute path, including filename, of that file. The default value, os.path.join(BASE_DIR, 'db.sqlite3'), will store the file in your project directory.
 
 You can also set others options like: TIME_ZONE, LANGUAGE_CODE, TEMPLATE…
 If you are not using SQLite as your database, additional settings such as USER,
 PASSWORD, and HOST must be added. 

 INSTALLED_APPS setting at the top of the file. That holds the names of all Django 
applications that are activated in this Django instance. Apps can be used in 
multiple projects, and you can package and distribute them for use by others in
their projects.By default,INSTALLED_APPS contains the following apps, all of which
come with Django:
 
 
  • django.contrib.admin – The admin site. You’ll use it shortly.
  • django.contrib.auth – An authentication system.
  • django.contrib.contenttypes – A framework for content types.
  • django.contrib.sessions – A session framework.
  • django.contrib.messages – A messaging framework.
  • django.contrib.staticfiles – A framework for managing static files.
 
 These applications are included by default as a convenience for the common case.
 we have our "myproj" application, now we need to register it with our 
 Django project "myproject". To do so, update INSTALLED_APPS tuple in the
 settings.py file of your project (add your app name)
 Some of these applications make use of at least one database table, though,
so we need to create the tables in the database before we can use them. To do
that, run the following command:

                    
$ python manage.py migrate

 
 The migrate command looks at the INSTALLED_APP setting
and creates any necessary database tables according to the database settings
in your pysite/settings.py file and the database migrations shipped
with the app. You’ll see a message for each migration it applies.
 If you’re interested, run the command-line client for your
database and type \dt (PostgreSQL), SHOW TABLES; (MySQL), .schema
(SQLite), or SELECT TABLE_NAME FROM USER_TABLES; (Oracle) to display the
tables Django created.
 
 

THANKS FOR VIEWING MY BLOG NEXT POST IS ON "CREATING MODELS" HOPE YOU LIKE THIS BLOG PLEASE COMMENT YOUR SUGGESTIONS AND SHARE THIS BLOG TO YOUR FRIENDS AND DON'T FORGET TO FOLLOW THIS BLOG