Nothing Special   »   [go: up one dir, main page]

Crud App Django

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 7

CRUD Application in Django

first of all, install python components and dbms - mariadb, in my case.

sudo apt-get update


sudo apt-get install python-pip python-dev mariadb-server libmariadbclient-dev
libssl-dev

configuring dbms:
sudo mysql_secure_installation

then we shall create database and database user:


mysql -u root -p
CREATE DATABASE ip2 CHARACTER SET UTF8;
CREATE USER myadmin@localhost IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON ip2.* TO myadmin@localhost;
FLUSH PRIVILEGES;
exit

follow by installing and configuring virtualenv:


sudo pip install virtualenv
mkdir ~/myproject
cd ~/myproject
virtualenv --python=python3.4 myprojectenv
source myprojectenv/bin/activate

now, install django and mysqlclient package:


pip install django mysqlclient

start project:
django-admin.py startproject myproject .

configure database setting in settings.py


nano ~/myproject/myproject/settings.py

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'myproject',
'USER': 'myprojectuser',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '',
}
}

migrate project and create superuser:


cd ~/myproject
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser

run server and see the result in browser:


python manage.py runserver

now, start the application:


python manage.py startapp dbapp

next, open settings.py and add our app to INSTALLED_APPS section


after that, create model and make makemigrations and migrate:
from django.db import models
from django.core.urlresolvers import reverse

# Create your models here.

class Data(models.Model):
Familiya = models.CharField(max_length=50, null=True)
Imya = models.CharField(max_length=50, null=True)
Otchestvo = models.CharField(max_length=50, null=True)
gr = models.CharField(max_length=50, null=True)
IP = models.CharField(max_length=50, null=True)
host = models.CharField(max_length=50, null=True)
edit_date = models.DateField(null=True)

def __unicode__(self):
return self.Imya + self.Familiya

def get_absolute_url(self):
return reverse('data_edit', kwargs={'pk': self.pk})

views:
from django.shortcuts import render, redirect, get_object_or_404
from django.forms import ModelForm
# Create your views here.

from dbapp.models import Data

class DataForm(ModelForm):
class Meta:
model = Data
fields = ['Familiya', 'Imya', 'Otchestvo', 'gr', 'IP', 'host',
'edit_date']

def ip_list(request,
template_name='dbapp/ip_list.html'):
ips = Data.objects.all()
alldata = {}
alldata['object_list'] = ips
return render(request, template_name, alldata)

def ip_create(request,
template_name='dbapp/ip_form.html'):
form = DataForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('ip_list')
return render(request, template_name, {'form':form})

def ip_update(request, pk,


template_name='dbapp/ip_form.html'):
ips = get_object_or_404(Data, pk=pk)
form = DataForm(request.POST or None, instance=ips)
if form.is_valid():
form.save()
return redirect('ip_list')
return render(request, template_name, {'form':form})
def ip_delete(request, pk,
template_name='dbapp/ip_confirm_delete.html'):
ips = get_object_or_404(Data, pk=pk)
if request.method=='POST':
ips.delete()
return redirect('ip_list')
return render(request, template_name, {'object':ips})

define urls:
"""ip2 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin

from dbapp import views

# urlpatterns = patterns('',
# url(r'^admin/', admin.site.urls),
# url(r'^$', views.ip_list, name='ip_list'),
# url(r'^new$', views.ip_create, name='ip_new'),
# url(r'^edit/(?P<pk>\d+)$', views.ip_update, name='ip_edit'),
# url(r'^delete/(?P<pk>\d+)$', views.ip_delete, name='ip_delete'),
# )

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.ip_list, name='ip_list'),
url(r'^new$', views.ip_create, name='ip_new'),
url(r'^edit/(?P<pk>\d+)$', views.ip_update, name='ip_edit'),
url(r'^delete/(?P<pk>\d+)$', views.ip_delete, name='ip_delete'),
]

and templates:
ip_confirm_delete.html
<form method="post">{% csrf_token %}
Are you sure you want to delete "{{ object }}" ?
<input type="submit" value="Submit" />
</form>

ip_form.html:
<form method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>

ip_list.html:
<h1>Woooooorking</h1>
<table>
<tr>
<th>������</th>
<th>��</th>
<th>��������</th>
<th>������</th>
<th>IP</th>
<th>Hostname</th>
<th>���� ��������</th>
</tr>
{% for user in object_list %}
<tr>
<td>{{ user.Familiya }}</td>
<td>{{ user.Imya }}</td>
<td>{{ user.Otchestvo }}</td>
<td>{{ user.gr }}</td>
<td>{{ user.IP }}</td>
<td>{{ user.host }}</td>
<td>{{ user.edit_date }}</td>
<td><a href="{% url 'ip_edit' user.id %}">��������</a></td>
<td><a href="{% url 'ip_delete' user.id %}">�������</a></td>
</tr>
{% endfor %}
</table>
<a href="{% url 'ip_new' %}">��������</a>

check if everything working by running server:


python manage.py runserver

now, if you have database with data, import it:


mysql -u root -p ip2 < database.sql

and insert data to our table:


INSERT INTO OUR_TABLE SELECT * FROM JUST_IMPORTED_TABLE;

NOW we need to implement search and require login and pass. and prettify
everything, of course.

Prompt users to login:


First, make sure that you've got django.contrib.auth in your INSTALLED_APPS.
We will login with user which we created with createsuperuser command above.
Add following lines in urls.py:

from django.contrib.auth import views as auth_views

urlpatterns = [
url(r'^$', auth_views.login, {'template_name': 'login.html'}, name='login'),
]

then, add this to settings.py:


LOGIN_REDIRECT_URL = 'ip_list'
LOGIN_URL = 'login'

Add login.html page:


{% extends "base.html" %}

{% block content %}
<h2>Login</h2>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
{% endblock content %}

Then add following lines to views.py:


from django.contrib.auth.decorators import login_required

@login_required #on top of every function

Now, lets add bootstrap and prettify application. create folder static
in app's folder in django, then copy
bootstrap files to static folder and include .css files u need
in base.html like that:
{% load staticfiles %} - at the very top

<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">


<link rel="stylesheet" href="{% static 'css/bootstrap-theme.min.css' %}">
<link rel="stylesheet" href="{% static 'css/blog.css' %}">
<script src="{% static "js/bootstrap.js" %}"></script>

About base.html - we need to make one base page and other pages will
inherit base html structure from it. Cretae folder templates in root directory of
project, inside it create base.html file, with basic html markdown, but it will
have blocks, contents of which will change depending on template. This blocks
are declared like this:
{% block content %}
{% endblock content %}

optional: put this on github


Create repository on github and then:
git init
git status
git add --all
git status
git commit -m "initial commit"
git remote add origin https://github.com/temurp/ip2.git
git push -u origin master

Now lets deploy our website:


tip - use local repisotory - mirrors.eastera.tj/ubuntu (/etc/apt/sources.list)

If we are deploying on a new server, update and upgrade it first, it is better to


use
local repository for the sake of speed.

sudo apt-get update


sudo apt-get upgrade

Installing required packages:


(python2)sudo apt-get install git python-pip apache2 libapache2-mod-wsgi python-dev
mariadb-server libmariadbclient-dev libssl-dev
(python3)sudo apt-get install git python3-pip apache2 libapache2-mod-wsgi-py3
python-dev mariadb-server libmariadbclient-dev libssl-dev

DB configuration:
sudo mysql_secure_installation
mysql -u root -p
CREATE DATABASE ip2 CHARACTER SET UTF8;
CREATE USER myadmin@localhost IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON ip2.* TO myadmin@localhost;
FLUSH PRIVILEGES;
exit

clone projects code from github:


git clone https://github.com/temurp/ip2.git

installing and configure virtualenv:


sudo pip install virtualenv
virtualenv myprojectenv --python=python3.4
source myprojectenv/bin/activate
pip install django mysqlclient

add this to settings.py:


STATIC_ROOT = os.path.join(BASE_DIR, "static/")

Next:
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py collectstatic
python manage.py runserver

Inserting data from other databases:


mysql -u myadmin -p ip2 < some_data.sql
mysql -u myadmin -p
use ip2;
insert into my_table select * from some_data_table.sql;
exit

deactivate

Now lets configure apache:


first of all, lets get rid of one small but annoying mistake by doing so (relevant
for ubuntu 14.04):

echo "ServerName localhost" | sudo tee /etc/apache2/conf-available/fqdn.conf


sudo a2enconf fqdn

next:
sudo nano /etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
. . .

Alias /static /home/user/ip2/static


<Directory /home/user/ip2/static>
Require all granted
</Directory>

<Directory /home/user/ip2/ip2>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIDaemonProcess ip2 python-path=/home/user/ip2 python-
home=/home/user/myprojectenv
WSGIProcessGroup ip2
WSGIScriptAlias / /home/user/ip2/ip2/wsgi.py

</VirtualHost>

sudo chown :www-data ~/ip2


sudo service apache2 restart

THATS IT!
now check in browser if your web-site is available.

Links:
https://rayed.com/wordpress/?p=1266
https://www.digitalocean.com/community/tutorials/how-to-use-mysql-or-mariadb-with-
your-django-application-on-ubuntu-14-04
https://simpleisbetterthancomplex.com/tutorial/2016/06/27/how-to-use-djangos-built-
in-login-system.html
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-
with-apache-and-mod_wsgi-on-ubuntu-14-04

You might also like