Python‎ > ‎django‎ > ‎

django.http


Examples
Here in this example, the CharField  is used to store the data into the field.  The data is recorded and saved in models.py and retrieved and displayed through the views.py. 
 Steps for creating virtual environment, startproject, startapp, creating database, and migrating the data, and running server to check the app.
  • virtualenenv djangoschool
  • cd djangoschool
  • .\Scripts\activate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • python manage.py migrate
  • python manage.py startapp dbapp
  • python manage.py makemigrations dbapp


mysite/settings,py

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

mysite/urls.py

from django.conf.urls import include, url

from dbapp.views import Display

urlpatterns = [
    url(r'^', Display),
]

dbapp/models.py


    groups=(('male','0-40'),('female','0-40'))
    genderfield=models.CharField(max_length=50,choices=groups)

v=LongLife(genderfield="Casey")
v.save()

dbapp/views.py



from . models import LongLife

def Display (request):
    return HttpResponse(LongLife.objects.filter(genderfield="Casey").values())







Here, in this example, the IntegerField validated number entered should be in record and before the Field vale is passed on HttpResponseRedirect in views.py and index.html files.
Steps for creating virtual environment, startproject, startapps, & running server:
  • virtualenv myvirtualenv
  • cd  mysite
  • .\Scripts\activate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • cd mysite
  • python manage.py startapp myapphttp
  • python manage.py runserver 



setting.py

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

urls.py

from django.conf.urls import include, url

from myapphttp.views import response

urlpatterns = [
      url(r'^', response),
]

myapphttp/forms.py

from django import forms



def Validate(value):
    pin=[1101,2945,3635,5550,3334,5553,2822,4624,3221,6453,2223,4456,5462]
    if value not in pin:
        raise ValidationError('%s : The pin number is not in our record.'% value)

class IntegerField(forms.Form):
    number=forms.IntegerField(label='Number' ,validators=[Validate])

myapphttp/views.py

from django.shortcuts import render

from .forms import IntegerField

def response(request):
    if request.method == 'POST':
        form=IntegerField(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/Thanks-for-submitting-your-request/')
    else:
        form = IntegerField()

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


myapphttp/index.html

<!DOCTYPE html>
<html>
<title> </title>
<body>

<form action="/pin-not-found/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>

</body>
</html>






Here, in this examples, the form validation is processed through the calling the function in the forms.EmailField(). The  function validated the list items after the form is submitted through POST method.
 Steps for creating virtual environment, startproject, startapps, & running server:
  • virtualenv myenv
  • cd  myenv
  • .\Scripts\activate
  • .\Scripts\deactivate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • cd mysite
  • python manage.py startapp myapp
  • python manage.py runserver

Files


setting.py

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

urls.py

from myapp.views import submit

urlpatterns = [
    url(r'^', submit),
]

myapp/forms.py

from django import forms
from django.core.exceptions import ValidationError

def Validate(email):
    list=['adil@adilwaseem.com', 'adil@pythonlake.com','contact@adilwaseem.com']
    if email not in list:
        raise ValidationError("%s is not in our record."% email )

class AccessForm(forms.Form):
    email=forms.EmailField(label='Email',validators=[Validate])

myapp/views.py

from django.shortcuts import render

from .forms import AccessForm

def submit(request):
    if request.method == 'POST':
        form=AccessForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/thanks/')
    else:
        form = AccessForm()

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

myapp/index.html

<!DOCTYPE html>
<html>
<title> </title>
<body>

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

</body>
</html>

view at localhost:8000/








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.







    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



      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

        Subpages (24): View All
        Comments