Python‎ > ‎django‎ > ‎

django.contrib


Example
The registration form is created using models in which user is allowed to register for news letter. model.py fields are import into the forms.py using class Meta.

Window CMD  commands 

  • virtualenv pythonlake
  • cd  pythonlake
  • .\Scripts\activate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • cd mysite
  • python manage.py startapp myapp
  • python manage.py syncdb
  • python manage.py runserver

Files


mysite/settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles','myapp',
) 

mysite/urls.py

from django.contrib import admin
admin.autodiscover()
from myapp.views import Register, Response

urlpatterns = patterns('',
    # Examples:
    url(r'^$', Register),
     url(r'^thanks/$', Response),

    url(r'^admin/', include(admin.site.urls)),
)

myapp/admin.py

from django.contrib import admin

from .models import Reg

    class Meta:
        model=Reg

admin.site.register(Reg,RegAdmin)

myapp/models.py

from django.db import models
class Reg(models.Model):
    first_name=models.CharField(max_length=100)
    last_name=models.CharField(max_length=100)
    email=models.EmailField()
    

myapp/forms

from django import forms
from .models import Reg

class RegForm(forms.ModelForm):
    class Meta:
        model=Reg

myapp/views.py

from django.shortcuts import render
from .forms import RegForm
from django.http import HttpResponse

def Register(request):

    form=RegForm(request.POST)
    if form.is_valid():
        save_form=form.save(commit=False)
        save_form.save()
        return HttpResponseRedirect('/thanks/')
    else:
        form=RegForm()

    return render(request, 'myapp\index.html', {'form':form})

def Response(request):
    return HttpResponse('Thanks for registering with us')

myapp/index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

<h1> Register for latest news</h1>

<form  action="" method="post">

    {%csrf_token%}

    {{form.as_p}}

    <input type="submit">

</form>

</body>
</html>






Example
The django web framework returns with hyperlink created through html5 integrated with django Scripts.
Steps for creating virtual environment, startproject, startapps, migration, & running server:
    • virtualenv string
    • cd  string
    • .\Scripts\activate
    • pip install django
    • python .\Scripts\django-admin.py startproject str
    • cd str
    • python manage.py runserver
    • key ctr c to break the server
    • python manage.py startapp htmlapp
    • python manage.py runserver

    File structure 




    settings.py

    INSTALLED_APPS = (
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles','htmlapp',
    )

    urls.py

    from django.conf.urls import url, patterns
    from htmlapp.views import html_links

    urlpatterns = patterns('',

        url(r'^html_links/', html_links),
        )

    httpapp/views.py


    def html_links(request):
        link='<div style="background-color:pink; color:white; padding:20px;">'\
             '<a href="http://www.pythonlake.com/">Python Lake</a> <hr>' \
             '<a href="http://www.pythonlake.com/python/django">Django</a> <hr> ' \
             '<a href="http://www.pythonlake.com/python/django/djangohttp">django.http</a> <hr> ' \
             '<a href="http://www.pythonlake.com/python/django/djangohttp/httpresponse">HttpResponse</a> <hr> ' \
             '</div>'
        return HttpResponse(link)


    Running the server through Window CMD command.





    Example
    The django web framework is used to create the application which convert the string into uppercase using str.upper method. The string_method_upper.py calls the string_method.views.py file to render the function.
    Windows CMD commands for creating virtualenv, startproject, startapp, and running server.
    • virtualenv string
    • cd string
    • .\Scripts\activate
    • pip install django
    • python .\Scripts\django-admin.py startproject str
    • cd str
    • python manage.py runserver
    • python manage.py startapp string_methods
    • python manage.py startapp string_method_upper
    • python manage.py runserver



    string_method_upper/views.py


    def string_method_upper (request):
        return string_upper(request)

    string_methods/views.py


    def string_upper(request):
        return HttpResponse("Python is a simple, powerful and high-level programming language "
                            "and the logic and structure is consistent with the way we "
                            "reasons. ".upper())


    urls.py

    from string_methods.views import*
    from string_method_upper.views import *

    urlpatterns=patterns('', url(r'^string_method_upper/', string_method_upper),)

    settings.py

    INSTALLED_APPS = (
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles','string_methods', 'string_method_upper',
    )





    Example
    The app is created to count the words in string using django web framework.
     Django Window CMD Commands
    Steps for creating virtual environment, startproject, startapps, migration, & running server:
    • virtualenv string
    • cd  string
    • .\Scripts\activate
    • .\Scripts\deactivate
    • pip install django
    • python .\Scripts\django-admin.py startproject str
    • cd str
    • python manage.py runserver
    • ctr c to stop server
    • python manage.py startapp string_methods
    • python manage.py migrate
    • python manage.py runserver
    FILE STRUCTURE
     
    In views.py file, the string value is added  by '%' expression to add str.count(). 
    from django.http import HttpResponse

    def count_chr(request):

        x="Python Lake is a project of OnRails LLC, founded by Adil Waseem with a mission to put all" \
          " Python Programming codes in one website with research findings for beginner, developer and " \
          "researcher to advance the development of Python. Internet is flooded with the Python codes but" \
          " all are deficient in comprehensiveness where we could find all functions in place with the" \
          " examples how and where to apply these. Python Lake will achieve this mission to promote learning" \
          " and research of Python without constraint by the lack of code examples and its application. " \
          "The site will be kept update periodically to allow students, developer and researcher them make" \
          " best of available resources in Python."
        y=x.count('Python')
        response = "Total words start with 'Python' in paragraphs are:%s"
        return HttpResponse(response%y)
     
    In settings.py file,  apps name is added.
    INSTALLED_APPS = (
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles','string_methods'
    )
    In urls.py file, following code is added to allow the apps to import function from the views.py.
     from django.conf.urls import include, url
    from django.contrib import admin

    from string_methods.views import count_chr

    urlpatterns = [
        url(r'^string_methods/', count_chr),
    ]
     
    Viewing in the browser after running server through CMD command.
     
     


    The function calculated string 'turtle' in webpage in django.
    STEPS for creating virtual environment, startproject, startapps, migration, & running server.
    • virtualenv [virtual environment name]
    • cd  [virtual environment name]
    • .\Scripts\activate
    • .\Scripts\deactivate
    • pip install django
    • python .\Scripts\django-admin.py startproject [project name]
    • cd [project name]
    • python manage.py runserver
    • python manage.py startapp [name of app]
    • python manage.py migrate
    • python manage.py runserver
     After virtual environment, startproject, and startapp, the files structure look like this:


      In setting.py, put following intended app name, here it is newrequests.
      INSTALLED_APPS = (
          'django.contrib.admin',
          'django.contrib.auth',
          'django.contrib.contenttypes',
          'django.contrib.sessions',
          'django.contrib.messages',
          'django.contrib.staticfiles','newrequests',
      )

      In urls.py, put following code: 
      from django.conf.urls import include, url
      from django.contrib import admin

      from newrequests.views import request1

      urlpatterns = [
          url(r'^newrequests/$', request1),
      ]

      In views.py, put following code:
      from django.http import HttpResponse
      import requests

      def request1(request):
          r=requests.get('http://www.pythonlake.com/Python/turtle')
          c=r.text
          ct=c.count('turtle')
          return HttpResponse(ct)
       
      Running the server at localhost:8000 through following command in CMD:
       python manage.py runserver



      The function calculated string 'turtle' in webpage in django.
      STEPS for creating virtual environment, startproject, startapps, migration, & running server.
      • virtualenv [virtual environment name]
      • cd  [virtual environment name]
      • .\Scripts\activate
      • .\Scripts\deactivate
      • pip install django
      • python .\Scripts\django-admin.py startproject [project name]
      • cd [project name]
      • python manage.py runserver
      • python manage.py startapp [name of app]
      • python manage.py migrate
      • python manage.py runserver
       After virtual environment, startproject, and startapp, the files structure look like this:


        In setting.py, put following intended app name, here it is newrequests.
        INSTALLED_APPS = (
            'django.contrib.admin',
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.messages',
            'django.contrib.staticfiles','newrequests',
        )

        In urls.py, put following code: 
        from django.conf.urls import include, url
        from django.contrib import admin

        from newrequests.views import request1

        urlpatterns = [
            url(r'^newrequests/$', request1),
        ]

        In views.py, put following code:
        from django.http import HttpResponse
        import requests

        def request1(request):
            r=requests.get('http://www.pythonlake.com/Python/turtle')
            c=r.text
            ct=c.count('turtle')
            return HttpResponse(ct)
         
        Running the server at localhost:8000 through following command in CMD:
         python manage.py runserver



        Here, HttpResponse returns with value of pow() through django web framework.
        STEPS for creating virtual environment, startproject, startapps, migration, & running server.
        • virtualenv [virtual environment name]
        • cd  [virtual environment name]
        • .\Scripts\activate
        • .\Scripts\deactivate
        • pip install django
        • python .\Scripts\django-admin.py startproject [project name]
        • cd [project name]
        • python manage.py runserver
        • python manage.py startapp [name of app]
        • python manage.py migrate
        • python manage.py runserver
         After virtual environment, startproject, and startapp, the files structure look like this:


          In setting.py, put following app name, here it is powapp.
          INSTALLED_APPS = (
              'django.contrib.admin',
              'django.contrib.auth',
              'django.contrib.contenttypes',
              'django.contrib.sessions',
              'django.contrib.messages',
              'django.contrib.staticfiles','powapp',
          )

          In urls.py, put following code: 
          from django.conf.urls import include, url
          from django.contrib import admin

          from powapp.views import func_pow

          urlpatterns = [
              url(r'^powapp/$', func_pow),
          ]

          In views.py, put following code:
          from django.shortcuts import render
          from django.http import HttpResponse

          def func_pow(request):
              return HttpResponse(pow(4,5))
           
          Running the server at localhost:8000 through following command in CMD:
           python manage.py runserver