Está en la página 1de 4

EXMEN DE FEBRERO: Proyecto de agencia de viajes. Dos carpetas dentro de la principal: AgenciaViajes, y Viajes (aplicacin). Adems, fuera, agencia.

db (base de datos) y manage.py


PRINCIPAL: Carpeta AgenciaViajes. Archivos: urls.py. Adems, dentro, carpeta TEMPLATES (html) (hay que modificar ** ARCHIVO urls.py ** )
VIAJES(APLICACION):Archivos: views.py, models.py, forms.py, admin.py, urls.py, test.py, __init__.py (vacio) Despues, generar paquetes.db
****** ARCHIVOS DE LA APLICACIN!!!! **********
** ARCHIVO views.py **
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404, redirect, render_to_response
from django.conf import settings
from django.http import HttpResponseRedirect
from .models import *
from .forms import *
from django.template import RequestContext, loader
from django.contrib.auth import authenticate, login, logout
from django.views.generic.base import View
from django.views.generic import TemplateView
#Destinos
def verDestino (request):
dest = Destino.objects.all()
context = {'destinos':dest}
return render(request, 'verDestino.html', context)
def detalleDestino (request, destino_id):
dest = Destino.objects.get(pk=destino_id)
context = {'destinoDetalle':dest}
return render(request, 'detalleDestino.html', context)
def addDestino(request):
if request.method == 'POST' :
dest = Destino()
formulario = DestinoForm (request.POST, instance = dest)
if formulario.is_valid():
formulario.save()
return HttpResponseRedirect('/')
else :
formulario = DestinoForm()
return render_to_response ('addDestino.html', {'formulario':formulario}, context_instance = RequestContext(request))
#Viajes
def verViajes (request):
via = Viaje.objects.all()
context = {'viajes':via}
return render(request, 'verViajes.html', context)
def addViaje(request):
if request.method == 'POST' :
via = Viaje()
formulario = ViajeForm (request.POST, instance = via)
if formulario.is_valid():
formulario.save()
return HttpResponseRedirect('/')
else :
formulario = ViajeForm()
return render_to_response ('addViaje.html', {'formulario':formulario}, context_instance = RequestContext(request))
def detalleViaje (request, viaje_id):
via = Viaje.objects.get(pk=viaje_id)
context={'viajeDetalle':via}
return render(request,'detalleViaje.html',context)
def editarViaje(request, viaje_id):
viaje = get_object_or_404(Viaje, pk = viaje_id)
if request.method == 'POST':
formulario = ViajeForm(request.POST, instance = viaje)
if formulario.is_valid():
formulario.save()
return HttpResponseRedirect('/')

else:
formulario = ViajeForm(instance = viaje)
context = { 'formulario': formulario,}
return render_to_response('editarViaje.html', context, context_instance=RequestContext(request))
#Usuarios
def userLogin(request):
if request.method == 'POST':
formulario = AuthenticationForm(request.POST)
if formulario.is_valid:
user = request.POST['username']
passwd = request.POST['password']
access = authenticate(username=user, password=passwd)
if access is not None:
if access.is_active:
login(request, access)
return redirect('/')
else:
return render(request, 'inactive.html')
else:
return render(request, 'nouser.html')
else:
formulario = AuthenticationForm()
context = {'formulario': formulario}
return render(request,'login.html', context)
@login_required(login_url='/login')
def userLogout(request):
logout(request)
return redirect('/')
#Rutas:
class verRuta(View):
template_name = 'verRuta.html'
def get(self, request, *args, **kwargs):
rutas = Ruta.objects.all()
return render(request, self.template_name, {'rutas':rutas})
class addRuta(View):
form_class = RutaForm
template_name = 'addRuta.html'
def get(self, request, *args, **kwargs):
formulario = self.form_class()
return render(request, self.template_name, {'formulario': formulario})
def post(self, request, *args, **kwargs):
formulario = self.form_class(request.POST, request.FILES)
if formulario.is_valid():
formulario.save()
return HttpResponseRedirect('/')
return render(request, self.template_name, {'formulario': formulario})
class detalleRuta(View):
template_name = 'detalleRuta.html'
def get(self, request, *arg, **kwargs):
id = self.kwargs['Ruta_id']
ruta = get_object_or_404(Ruta, pk = id)
return render(request,self.template_name,{'rutaDetalle':ruta,'user':request.user})

** ARCHIVO models.py **
from django.db import models
from django.utils.encoding import smart_unicode
from django.contrib.auth.models import User
from django.contrib import admin
# Un destino es un lugar al que se puede viajar, pero sin incluir los datos respecto al viaje, como precio, etc...
class Destino(models.Model):
lugar = models.CharField(max_length=100)
descripcion = models.TextField()
distancia = models.IntegerField()
def __unicode__(self):
return self.lugar
class Viaje (models.Model):
destino = models.ForeignKey(Destino)
numero_de_dias = models.IntegerField()
coste = models.IntegerField()
modo_desplazamiento = models.CharField(max_length=100)
def __unicode__(self):
return (self.destino.lugar)
class Ruta(models.Model):
Nombre_Ruta = models.CharField(max_length=100)
Destinos = models.ManyToManyField(Destino)
Precio_total= models.IntegerField()
Duracion_Total= models.IntegerField()
def __unicode__(self):
return (self.Nombre_Ruta)
** ARCHIVO forms.py **
from django.forms import ModelForm
from django import forms
from .models import *
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class DestinoForm (forms.ModelForm):
class Meta:
model = Destino
class ViajeForm (forms.ModelForm):
class Meta:
model = Viaje
class RutaForm (forms.ModelForm):
class Meta:
model = Ruta
class AuthenticationForm(ModelForm):
class Meta:
model = User
fields = ['username', 'password']
widgets = {
'password': forms.PasswordInput(),
}

** ARCHIVO admin.py **
from django.contrib import admin
from viajes.models import *
admin.site.register(Destino)
admin.site.register(Viaje)
admin.site.register(Ruta)
** ARCHIVO urls.py **
from django.conf.urls import patterns, include, url
from viajes import views
from .views import *
#ojo, abajo hay comillas simples!
urlpatterns = patterns ('',
#Destinos
url (r'^verDestino', views.verDestino, name='Ver Destinos'),
url (r'^detalleDestino/(?P<destino_id>\d+)', views.detalleDestino, name='Detalles Destino'),
url (r'^addDestino', views.addDestino, name='Anadir Destino'),
#Viajes
url (r'^verViajes', views.verViajes, name='Ver Viajes'),
url (r'^addViaje', views.addViaje, name='Anadir Viaje'),
url (r'^detalleViaje/(?P<viaje_id>\d+)', views.detalleViaje, name='Detalles de Viaje'),
url (r'^editarViaje/(?P<viaje_id>\d+)$', views.editarViaje, name='Editar Viaje'),
#Rutas (con Vistas basadas en clases)
url (r'^verRuta', verRuta.as_view(), name='Ver Ruta'),
url (r'^addRuta', addRuta.as_view(), name='Anadir Ruta'),
url (r'^detalleRuta/(?P<Ruta_id>\w+)$', detalleRuta.as_view(), name='Detalles Ruta'),
)
** ARCHIVO test.py **
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
** no olvidar crear el __init__.py que si no esta, el programa peta!!!!! **
***************

ARCHIVOS HTML DE LA APLICACIN: Subcarpeta dentro, llamada templates

addRuta.html
<html>
<head>
<title> Viajes </title>
<h1> Lista de viajes</h1>
</head>
<body>
{% if viajes %}
<ul>
{% for x in viajes %}
<a href =/viajes/detalleViaje/{{x.id}}><li> {{x.destino}} </li>
{% endfor %}
</ul>
{% else %}
<h3> No hay viajes </h3>
{% endif %}
</body>
</html>

**************

* addDestino.html
<html>
<head>
<title> Aadir Destino </title>
</head>
<body>
<h1> Aadir Destino </h1>
<form id='formulario' method='post' enctype='multipart/form-data' action=''>
{% csrf_token %}
{{ formulario.as_p }}
<input type="submit" value="Enviar"/>
</form>
</body>
</html>
* addViaje.html
<html>
<head>
<title> Aadir Viaje </title>
</head>
<body>
<h1> Aadir Viaje </h1>
<form id='formulario' method='post' enctype='multipart/form-data' action=''>
{% csrf_token %}
{{ formulario.as_p}}
<input type="submit" value="Enviar"/>
</form>
</html>
* detalleDestino.html
<html>
<head>
<title> Detalle de Destino </title>
</head>
<body>
Detalle de Destino
<ul>
<li> Lugar:{{destinoDetalle.lugar}} </li>
<li> Descripcion:{{destinoDetalle.descripcion}} </li>
<li> Distancia:{{destinoDetalle.distancia}} </li>
</ul>
</body>
</html>
* detalleRuta.html
<html>
<head>
<title> Detalles de Ruta </title>
</head>
<body>
Detalles de la Ruta
<ul>
<li> Nombre de la ruta: {{rutaDetalle.Nombre_Ruta}} </li>
{% if rutaDetalle.Destinos %}

* detalleViaje.html
<html>
<head>
<title> Detalles de {{viajeDetalle.destino}} </title>
</head>
<body>
<h1>Detalles del viaje: {{viajeDetalle.destino}} </h2>
<ul>
<li> Destino: {{viajeDetalle.destino}} </li>
<li> Numero de dias: {{viajeDetalle.numero_de_dias}} </li>
<li> Coste: {{viajeDetalle.coste}} </li>
<li> Modo de desplazamiento: {{viajeDetalle.modo_desplazamiento}} </li>
</ul>
<a href ="/viajes/editarViaje/{{viajeDetalle.id}}"> > Editar</a>
</body>
</html>
* editarViaje.html
<html>
<head>
<title> Editar Paquete </title>
</head>
<body>
<h1> Editar Paquete </h1>
<form id='formulario' method='post' enctype='multipart/form-data' action=''>
{% csrf_token %}
{{formulario.as_p}}
<input type="submit" value="Aceptar Edicin"/>
</form>
</body>
</html>
* inactive.html
{% extends 'index.html' %}
{% comment %} User login form {% endcomment %}
{% block title %} <h1>Error al acceder</h1> {% endblock %}
{% block content %}
<h2>Usuario no activo</h2>
{% endblock %}
* nouser.html
{% extends 'index.html' %}
{% comment %} User login form {% endcomment %}
{% block title %} <h1>Error al acceder</h1> {% endblock %}
{% block content %}
<h2>Usuario no encontrado o password incorrecta</h2>
{% endblock %}
* verDestino.html
<html>
<head>
<title> Destinos </title>
<h1> Lista de destinos</h1>
</head>
<body>
{% if destinos %}
<ul>
{% for x in destinos %}

<li>Destinos:{% for x in rutaDetalle.Destinos.all %}


{{x}}-

<a href =/viajes/detalleDestino/{{x.id}}><li> {{x.lugar}} </li>


{% endfor %}

{% endfor %}
</li>
{% endif %}

</ul>
{% else %}
<h1> No hay destinos </h1>
{% endif %}
</body>

<li> Precio Total: {{rutaDetalle.Precio_total}} </li>


<li> Duracin (en das): {{rutaDetalle.Duracion_Total}} </li>
</ul>
</body>
</html>

</html>

verRuta.html
<html>
<head>
<title> Rutas </title>
<h1> Lista de Rutas</h1>
</head>
<body>
{% if rutas %}
<ul>
{% for x in rutas %}
<a href =/viajes/detalleRuta/{{x.id}}><li>
{{x.Nombre_Ruta}} </li>
{% endfor %}
</ul>
{% else %}
<h3> No hay Rutas disponibles </h3>
{% endif %}
</body>
</html>
verViajes.html
<html>
<head>
<title> Viajes </title>
<h1> Lista de viajes</h1>
</head>
<body>
{% if viajes %}
<ul>
{% for x in viajes %}
<a href =/viajes/detalleViaje/{{x.id}}><li>
{{x.destino}} </li>
{% endfor %}
</ul>
{% else %}
<h3> No hay viajes </h3>
{% endif %}
</body>
</html>

********************Archivos del proyecto prncipal!!

********************* Carpeta AgenciaViajes

** ARCHIVO urls.py **
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.views.generic import TemplateView
from viajes import views
from viajes.views import verDestino
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

********************Archivos del proyecto prncipal!!


** ARCHIVO index.html **
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='utf-8'>
<title>Agencia de viajes virtual</title>
<body>
<h2>Bienvenido a la agencia de viajes virtual</h2>
</body>
{% block content %}

urlpatterns = patterns('',
# Examples:
url(r'^$', TemplateView.as_view(template_name='index.html'), name='index'),
# url(r'^AgenciaViajes/', include('AgenciaViajes.foo.urls')),

{% endblock %}
{% if user.is_authenticated %}
<h3> Bienvenido {{user.username}} </h3>
{% endif %}
{% if not user.is_authenticated %}
<a href="/login">Entrar</a>
{% endif %}

# Uncomment the admin/doc line below to enable admin documentation:


url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),

{% if user.is_authenticated %}
<a href="/logout">Salir</a>
{% endif %}

url(r'^viajes/', include ('viajes.urls', namespace = 'viajes')),

<h3>Destinos</h3>
<a href ="/viajes/verDestino"> <li>Ver destinos</li></a>
<a href ="/viajes/addDestino"> <li>Aadir destinos</li></a>

url (r'^login', views.userLogin, name='Login'),


url (r'^logout', views.userLogout, name='Logout'),
)
ARCHIVOS HTML (carpeta templates)

<h3>Viajes</h3>
<a href ="/viajes/verViajes"> <li>Ver Viajes</li></a>
<a href ="/viajes/addViaje"> <li>Aadir Viajes</li></a>

*** Archivo login.html ***


{% extends 'index.html' %}
{% block content %}
<form method="POST">{% csrf_token %}
<h2> Login </h2>
<input type="text" name="username" id="inputUsername" placeholder="Introduzca Usuario....">
<input type="password" name="password" id="inputPassword" placeholder="Introduzca Contrasea....">
<button type="submit">Entrar</button>
</form>
{% endblock %}
</html>

********************* Carpeta AgenciaViajes

<h3>Rutas</h3>
<a href ="/viajes/verRuta"> <li>Ver Rutas</li></a>
<a href ="/viajes/addRuta"> <li>Aadir Ruta</li></a>
</html>

También podría gustarte