Python‎ > ‎django‎ > ‎

django.shortcuts



Through the QuerySet, the db is diplay through view.py. Only latest object is query in this this example.

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

models.py

from django.db import models

class ModelUrl(models.Model):
    url=models.URLField()

    def __str__(self):
        return self.url

myapp/views.py

from .models import ModelUrl
def URL_List(request):
    model = ModelUrl
    context_object_name = 'Url'
    url=ModelUrl.objects.latest('id')
    string=str(url)
    return HttpResponse(string)

mysite/ulrs.py

from django.conf.urls import include, url

from myapp.views import URL_List

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

python manage.py runserver

 




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>





URLField is created through models and  viewed through index.html. 

Window CMD  commands 

  • virtualenv djangoschool
  • cd  djangoschool
  • .\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




mysite/setting.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.conf.urls import include, url

from myapp.views import ViewUrl
urlpatterns = [
    url(r'^', ViewUrl)
]


myapp/models.py

from django.db import models

class ModelUrl(models.Model):
    url=models.URLField()

    def __str__(self):
        return self.url


myapp/forms.py

from django import forms
from .models import ModelUrl

class FormUrl(forms.ModelForm):
    class Meta:
        model=ModelUrl
        fields=['url']


myapp/views.py

from django.shortcuts import render

from django.shortcuts import HttpResponseRedirectHttpResponse
from .forms import FormUrl

def ViewUrl(request):
    form=FormUrl(request.POST)
    if form.is_valid():
        form.save(commit=False)
        form.save()
        return HttpResponseRedirect('/thanks/')
    else:
        form=FormUrl
    return render(request, 'myapp/index.html',{'form':form})

def response(request):
    return HttpResponse("Thanks")

myapp/index.html

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

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

    {%csrf_token%}

    {{form}}

    <input type="submit">

</form>

</body>
</html>

Localhost:8000



Database Query




Example
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/








Here, the submit form is created through the django web framework using django.forms. The forms is handled through the HTML files in which the views.py variables data is processed. While views.py import the form fields from myapps/forms.py
Steps for creating steps for virtua 

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



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.conf.urls import url
from myapp.views import submit

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


myapp/forms.py

__author__ = 'adilwaseem75'

from django import forms

class CharField(forms.Form):
    username=forms.CharField()
    username.label="Username"
    username.max_length=50

class EmailField(forms.Form):
    email=forms.EmailField()
    email.label="Email"
    email.max_length=50


myapp.views.py

from django.shortcuts import render

from .forms import EmailField
from .forms import CharField

def submit(request):
    username=CharField()
    email=EmailField()

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

myapp.index.html

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

<form action="/Thank-you/" method="post">
    {% csrf_token %}
    {{username}} <br> <br>
    {{email}}<br><br>
    <input type="submit" value="Submit" />
</form>

</body>
</html>


Running the server through Window CMD command, python manage.py runserver




EXAMPLE
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