Python Django Part 4 - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript Python Django Part 4 - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript


Post Top Ad

Post Top Ad

Saturday, December 22, 2018

Python Django Part 4

Python Django Part4


The register view

The register view needs to display a blank registration from when the page is first requested, and then process completed registration forms. A successful registration logs the user in and redirects to the home page.

from djnago.contrib.auth import login
from django.contrib.auth import authenticate
from django.contrib.auth forms import \


def register(request):
"""Register a new user,"""
if request.method | ='post':
#Show blank registration form.
form = UserCreationForm()
#process completed form .
form = userCreationForm(
if form.is_valid():
new_user =
#log in , redirect to home page.
pw =[;passward1']
authenticated_user = authenticate (
username=new_uiser .username,password=pw


login(request, authenticated_user)

return httpresponse redirect(


context = {'form':form}

return render(request,

The django-bootstrap3 appallows you to use the bootstrap library to make your project l0ook visually appealing. The app provides tags that you can use in your templates to style individual elements on apage learn more at


Heroku lets you push your project to alive server,  making it available to anyone with an internet connection. heroku offers afree services level, which lets you learn the deployment process without any commitment. you will need to install a set of heroku tools and use git to track the site of your project.


The register template

The register template displays the registration form in paragraph formats.

{% extends 'learning_logs/base.html' %}
{% block content %}
<form method ='post'
action="{% url 'users:register'  %}">
{% csrf_token  %}
{{form.as_p }}
<button name='subit'>register</button>
<input type='hidden' name='next'
value="{ url 'learning_logs :index' %}"/>
{% endblock content %}


User will have date that belongs to them.Any model that should be connected directly to auser needs a field connecting instances of the model to a specific user.

#Making a topic belong to a user
#Only the highest level data in a hierarchy needs  to be directly connected to a user. To do this import the user model, and add it as a foregn key on the data model, and add it as a foregn key on the data model.

#After modifying the model you'll need to migrate the database You will need to chose a user ID to connect each existing instance to.

from djnago.db import models
from django.contrib.auth.models import user

class topic (models.model):

"""A topic the user is learning about ."""

text = models.charfield(max-length=200)

date_added = models.datetimefield(


owner = models.foreignkey(user)


return self.txt

#Querying data for the current user
#In a view, the request object has a user attribute. You can use this attribute to query for the user's data.The filter() function then pulls the data that belongs to the current user.

topics = Topic.objects.filter(owner=request.user)

Connecting data to users(cont.)

Restricting access to logged-in users
Some pages are only relevant to registered users. The views for these pages can be protected by the @login_required decorator. Any view with this decorator will automatically redirect non-logged in users to an appropriate page. Here's an example file.

from django.contrib.auth.decorators import / login_required

def topic(request, topic_id):
"""Show a topics and all its entries."""

Setting the redirect URL

The @login_required decorator sends unauthorized users to the login page. Add the following line to your project's file so Django will know how to find your login page.

LOGIN_URL = '/user/login/'

Preventing inadvertent access

Some pages serve data based on a parameter in the URL. You can check that the user owns the requested data, and return a 404 error if they don't. Here's an example view.

from django.http import Http404

def topic(request, topic_id):
"""show a topic and all its entries."""
topic = Topic.object.get(id=topic_id)
if topic.owner != request.user:
raise Http404

Using a form to edit data

If you provide some initial data. Django generates a form with the user's existing data. User can then modify and save their data.
Creating a form with initial data
The instance parameter allows you to specify initial data for a form

form = EntryForm (instance=entry)

Modifying data before saving

The argument commit=False allows you to make changes before writing data to the database.

new_topic.owner = request.user

No comments:

Post a Comment

Post Top Ad