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

Breaking

Post Top Ad

Post Top Ad

Saturday, December 22, 2018

Python Django Part 4

Python Django Part4



USER ACCOUNTS (CONT.)

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 \

userCreationForm


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

)

login(request, authenticated_user)

return httpresponse redirect(

reverse('learning_logs:index;))



context = {'form':form}

return render(request,

'users/register.html,context)
STYLING YOUR PROJECT
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 http://django-bootstrap.readthedocs.io/.

DEPLOYING YOUR PROJECT 

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.

USER ACCOUNTS (CONT.)

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' %}"/>
</form>
{% endblock content %}


CONNECTING DATA TO USERS

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(

auto_now_add=true)

owner = models.foreignkey(user)

def_str_(self):

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 views.py file.

from django.contrib.auth.decorators import / login_required
--snip--

@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 setting.py 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

--snip--
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
--snip--

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= form.save(commit=False)
new_topic.owner = request.user
new_topic.save()

No comments:

Post a Comment

Post Top Ad