Skip to content

Instantly share code, notes, and snippets.

Created September 30, 2011 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/fdd81a95d229a15401ee to your computer and use it in GitHub Desktop.
Save anonymous/fdd81a95d229a15401ee to your computer and use it in GitHub Desktop.
BDD_Materiaux
models.py
from django.db import models
from django.utils.translation import ugettext_lazy as _
import mptt
class Category(models.Model):
name = models.CharField(_('name'), max_length=50)
slug = models.SlugField()
description = models.TextField(_('description'), blank=True)
parent = models.ForeignKey('self', null=True, blank=True,
verbose_name=_('parent category'),
related_name='children')
@models.permalink
def get_absolute_url(self):
return ('materiaux_category_detail', (), {'slug': self.slug})
def get_materiaux(self):
return self.material_set.all()
def __unicode__(self):
return self.name
class Meta:
ordering = ['name']
verbose_name = _('category')
verbose_name_plural = _('categories')
mptt.register(Category, order_insertion_by=['name'])
class Material(models.Model):
name = models.CharField(_('name'), max_length=50)
description = models.TextField(_('description'), blank=True)
slug = models.SlugField()
category = models.ForeignKey(Category, verbose_name=_('category'))
def get_physical_properties(self):
return self.uniteproperty_set.all()
def get_medias(self):
return self.media2_set.all()
@models.permalink
def get_absolute_url(self):
return ('materiaux_material_detail', (), {'slug': self.slug})
def __unicode__(self):
return self.name
class Meta:
verbose_name = _('material')
verbose_name_plural = _('materials')
ordering = ['name']
class Property(models.Model):
name = models.CharField(_('name'), max_length=50)
description = models.TextField(_('description'), blank=True)
def __unicode__(self):
return self.name
class Meta:
verbose_name = _('property')
verbose_name_plural = _('properties')
class MaterialProperty(models.Model):
material = models.ForeignKey(Material, verbose_name=_('material'))
property_name = models.ForeignKey(Property, verbose_name=_('property'))
value = models.TextField(_('value'))
def __unicode__(self):
return '%s %s: %s' % (self.material.name, self.property_name.name, self.value)
class Meta:
verbose_name = _('material property')
verbose_name_plural = _('material properties')
class UniteProperty(models.Model):
name = models.ForeignKey(Material, verbose_name=_('name')) # composition chimique
nature_unit = models.ForeignKey(Property, verbose_name=_('nature_unit')) # categorie (mecanique, thermique...)
val_champ = models.CharField(_('val_champ'), max_length=50) # propriete physique, mecanique....
val= models.FloatField(blank=True, null=False) # valeur numerique
val_unit = models.CharField(_('val_unit'), max_length=50) # unite (GPa, Kg,....)
def __unicode__(self):
return '%s' % (self.name)
class Meta:
verbose_name = _('parameter')
verbose_name_plural = _('parametres')
ordering = ['-nature_unit']
class Media2(models.Model):
FORMAT_CHOICES = ((0, 'pdf'),
(1, 'jpeg'),
(2, 'xls'))
material = models.ForeignKey(Material, verbose_name=_('material'))
nature = models.ForeignKey(Property, verbose_name=_('nature'))
name = models.CharField(_('name'), max_length=50)
description = models.TextField(_('description'), blank=True)
source = models.FileField(_('source'), upload_to='medias')
format = models.IntegerField(_('format'), choices=FORMAT_CHOICES)
def __unicode__(self):
return '%s %s %s' % (self.nature, self.name, self.source)
class Meta:
verbose_name = _('media')
verbose_name_plural = _('medias')
url.py
from django.conf.urls.defaults import *
from monprojet.materiaux.models import Material, Media2
from monprojet.materiaux.models import Category
from monprojet.materiaux.views import *
from django.core.urlresolvers import reverse
from django.conf.urls.defaults import *
material_info = {"queryset" : Material.objects.all()}
category_root_info = {"queryset" : Category.tree.root_nodes()}
cat_info = {"queryset" : Category.objects.all()}
urlpatterns = patterns('django.views.generic.list_detail',
url(r'^$', 'object_list',
category_root_info, 'materiaux_category_root'),
url(r'^materiaux/$', 'object_list',
material_info, 'materiaux_material_list'),
url(r'^materiaux/(?P<slug>[-\w]+)/$', 'object_detail',
material_info, 'materiaux_material_detail'),
)
urlpatterns += patterns('monprojet.materiaux.views',
url(r'^category/(?P<slug>[-\w]+)/$', 'view_category_detail',
name='materiaux_category_detail'),
)
urlpatterns += patterns('',
url(r'^add/$', 'monprojet.materiaux.views.add_materiau', name='record'),
url(r'^nouv/$', 'monprojet.materiaux.views.nouveau_materiau', name='nouveau'),
url(r'^update/(?P<material_id>[-\w]+)$', 'monprojet.materiaux.views.manage2_materiaux', name='edition'),
url(r'^medias/(?P<material_id>[-\w]+)$', 'monprojet.materiaux.views.manage_medias', name='edition_media'),
url(r'^delete/(?P<slug>\d+)/$', 'monprojet.materiaux.views.delete_materiau', name='delete'),
url(r'^search/$', 'monprojet.materiaux.views.search', name='chercher'),
url('^filtre/$', 'monprojet.materiaux.views.search_filter', name='chercher_filtre'),
#url(r'^unit/(?P<id>\d+)$', 'monprojet.materiaux.views.lit_val', name='lit_param'),
url(r'^unit/(?P<id>\d+)$', 'monprojet.materiaux.views.convert', name='lit_param'),
url(r'^unit/$', 'monprojet.materiaux.views.affiche', name='toto'),
url(r'^conv/$', 'monprojet.materiaux.views.lit_conv', name='converti'),
url(r'^trait/(?P<id>\d+)$', 'monprojet.materiaux.views.lit_trait', name='traite'),
)
views.py
from django.db.models import Q
from django.shortcuts import get_object_or_404
from django.shortcuts import render_to_response
from django.views.generic.list_detail import object_list
from django.views.generic.list_detail import object_detail
from monprojet.materiaux.models import Category, Material, MaterialProperty, Property, UniteProperty, Media2
from django.http import Http404
from django.http import HttpResponseRedirect
from forms import MateriauForm, MatForm, nouveauForm, MaterialForm, Add
from django.core.urlresolvers import reverse
from django.views.generic.create_update import update_object
from django.views.generic.create_update import delete_object
from django.contrib.auth.decorators import login_required
from django.core import paginator #, EmptyPage, PageNotAnInteger
from django.forms.models import inlineformset_factory
from django.template import RequestContext
from monprojet.materiaux.units import unit_conversions, length
from forms import UnitConverterForm
from django.http import HttpResponse
@login_required
def view_category_detail(request, slug):
category = get_object_or_404(Category, slug=slug)
return object_list(request, queryset=category.get_children(),
extra_context={'category': category})
def list_category(request):
cats = Category.objects.filter(pk=id)
return render_to_response('sou_cat.html', {'cats': cats})
# filtrage par materiau
@login_required
def search(request):
errors = []
if 'q' in request.GET:
q = request.GET['q']
if not q :
return render_to_response('materiaux/message.html')
else:
materiau = Material.objects.filter(name__icontains=q)
return render_to_response('materiaux/search_results.html',
{'materiau': materiau, 'query': q})
return render_to_response(
{'errors': errors})
def search_filter(request):
errors = []
mat = []
q = []
val1 = []
materiaux = []
try:
if 'q' and 'fil' in request.GET:
q = int(request.GET['q'])
val1 = request.GET['fil'] # densite....
materiaux = Material.objects.all()
mat = UniteProperty.objects.filter(
Q(val_champ__icontains = val1) & Q(val__gt=q-0.1, val__lte=q))
except ValueError, error:
return render_to_response('materiaux/message.html',
locals(),
context_instance=RequestContext(request))
else:
pass
return render_to_response('materiaux/search_results_filt.html',
{'mat' : mat,
'materiaux' : materiaux,
'query': q,
# 'query': val2,
'query': val1,
})
return render_to_response(
{'errors': errors})
# ajout d'une nouvelle propriete d'un materiau
def add_materiau(request):
if request.method == 'POST':
form = MatForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('materiaux_material_list'))
else:
form = MatForm()
return render_to_response('materiaux/ajout_mat.html', {'form':form})
def nouveau_materiau(request):
if request.method == 'POST':
form = nouveauForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('materiaux_material_list'))
else:
form = nouveauForm()
return render_to_response('materiaux/ajout_nouveau.html', {'form':form})
def edit_materiau(request, id):
return update_object(request,
model=Media2,
object_id=id,
template_name='materiaux/update.html',
post_save_redirect=reverse('materiaux_material_list')
)
def manage_medias(request, material_id=None):
if material_id== None:
material = Material()
else:
material = Material.objects.get(id = material_id)
MaterialFormset = inlineformset_factory(Material, Media2, can_delete=True)
if request.method == "POST":
materialform = MaterialForm(request.POST, instance=material)
materialformset = MaterialFormset(request.POST,request.FILES, instance=material)
if materialform.is_valid():
materialform.save()
else:
#materialform = materialform()
pass
if materialformset.is_valid():
materialformset.save()
else:
#materialformset = materialformset()
pass
# if '_save' in request.POST:
# return HttpResponseRedirect(reverse('materiaux_material_list'))
# if '_addanother' in request.POST:
# return HttpResponseRedirect(reverse('materiaux_material_list'))
else:
materialform = MaterialForm(instance=material)
materialformset = MaterialFormset(instance=material)
return render_to_response('materiaux/manage_media.html', {
'material_id': material_id,
'materialform': materialform,
'materialformset' : materialformset,
})
def manage2_materiaux(request, material_id=None):
if material_id== None:
material = Material()
else:
material = Material.objects.get(id = material_id)
MaterialFormset = inlineformset_factory(Material, UniteProperty, can_delete=True)
if request.method == "POST":
materialform = MaterialForm(request.POST, instance=material)
materialformset = MaterialFormset(request.POST,request.FILES, instance=material)
if materialform.is_valid():
materialform.save()
else:
pass
if materialformset.is_valid():
materialformset.save()
else:
pass
# if '_save' in request.POST:
# return HttpResponseRedirect(reverse('materiaux_material_list'))
# if '_addanother' in request.POST:
# return HttpResponseRedirect(reverse('materiaux_material_list'))
else:
materialform = MaterialForm(instance=material)
materialformset = MaterialFormset(instance=material)
return render_to_response('materiaux/manage_materiaux.html', {
'material_id': material_id,
'materialform': materialform,
'materialformset' : materialformset,
})
@login_required
def delete_materiau(request, slug):
return delete_object(request,
model=Material,
object_id=slug,
template_name='materiaux/delete.html',
template_object_name='index',
post_delete_redirect=reverse('materiaux_material_list')
)
def delete_materialProperty(request, slug):
return delete_object(request,
model=MaterialProperty,
object_id=slug,
template_name='materiaux/delete.html',
template_object_name='indice',
post_delete_redirect=reverse('materiaux_material_list')
)
def mat_edit(request, id=None):
instance = None
if id is not None:
instance = UniteProperty.objects.get(id=id)
if request.method == "POST":
form = MatForm(request.POST, instance=instance)
if form.is_valid():
form.save()
return HttpResponseRedirect('/materiaux/')
else:
form = MatForm()
return render_to_response('mat_edit.html', {'form':form})
def lit_conv(request):
add = Add()
print add(10)
val1 = request.GET['q']
val2 = request.GET['fil']
val3 = request.GET['fil2']
return render_to_response('materiaux/calcul.html',
{'val1': val1,
'val2': val2,
'val3': val3,
})
def convert(request, id):
if request.method == 'POST':
queryset= UniteProperty.objects.all()
object_id=id
form = UnitConverterForm(request.POST)
if form.is_valid():
return HttpResponse('Value : %.2f' % form.convert())
else:
form = UnitConverterForm()
return render_to_response('materiaux/forms.html', {'form': form},
context_instance=RequestContext(request))
def affiche(request):
if request.method == 'POST':
form = UnitConverterForm(request.POST)
if form.is_valid():
var0 = form.convert() # resultat du calcul
return render_to_response('materiaux/calcul.html',
{'var0': var0,
})
else:
form = UnitConverterForm()
return render_to_response('materiaux/forms.html', {'form': form},
context_instance=RequestContext(request))
# chargement dans le formulaire de saisie de la donnee numerique correspondant au champ densite
def lit_val(request, id):
return object_detail(request,
queryset= UniteProperty.objects.all(),
object_id=id,
template_name='materiaux/charge_param.html',
template_object_name ='param'
)
def lit_trait(request, id):
return object_detail(request,
queryset= Material.objects.all(),
object_id=id,
template_name='materiaux/traite_param.html',
template_object_name ='param'
)
def view_material_list(request):
_material_list = models.Material.objects.all()
_paginator = paginator.Paginator(_material_list, 3) # Show 25 contacts per page
_page = request.GET.get('page') if 'page' in request.GET else 1
try:
_materials = _paginator.page(_page)
except paginator.PageNotAnInteger:
_materials = _paginator.page(1)
except paginator.EmptyPage:
_materials = _paginator.page(_paginator.num_pages)
# .. render it
return shortcuts.render_to_response('materiaux/list.html',
{"category": _materials})
forms.py
# -*- coding: utf-8 -*-
from monprojet.materiaux.models import Category, Material, MaterialProperty, UniteProperty, Media2
from django import forms
from django.contrib.admin.widgets import AdminTextInputWidget
from monprojet.materiaux.units import UNITS
UNITS_CHOICES = [(key, key) for key in UNITS.keys()]
class MateriauForm(forms.ModelForm):
class Meta:
model = Category
class MatForm(forms.ModelForm):
class Meta:
model = UniteProperty
class nouveauForm(forms.ModelForm):
class Meta:
model = Material
class MaterialForm(forms.ModelForm):
class Meta:
model = Material
class Media2Form(forms.ModelForm):
class Meta:
model = Media2
class UnitConverterForm(forms.Form):
value = forms.FloatField(label='Value')
unit_from = forms.ChoiceField(label='from', choices=UNITS_CHOICES)
unit_to = forms.ChoiceField(label='to', choices=UNITS_CHOICES)
def convert(self):
factor2 = UNITS[self.cleaned_data['unit_from']]
factor1 = UNITS[self.cleaned_data['unit_to']]
x = float(self.cleaned_data['value'])
return factor1*x/factor2
class Add(object):
def __init__(self):
self.count = 0
def __call__(self, value=None):
if value is not None:
self.count += int(value)
return self.count
def reset(self):
self.count = 0
admin.py
"""Admin for materiaux"""
from django.contrib import admin
from monprojet.materiaux.models import Material
from monprojet.materiaux.models import Media2
from monprojet.materiaux.models import Property
from monprojet.materiaux.models import MaterialProperty
from monprojet.materiaux.models import Category
from monprojet.materiaux.models import UniteProperty
class MediaInline(admin.StackedInline):
model = Media2
class MaterialPropertyInline(admin.TabularInline):
model = MaterialProperty
class UnitePropertyInline(admin.TabularInline):
model = UniteProperty
class MaterialAdmin(admin.ModelAdmin):
list_display = ('name', 'description')
prepopulated_fields = {'slug': ('name',)}
inlines = (MediaInline, UnitePropertyInline)
class PropertyAdmin(admin.ModelAdmin):
#list_display = ('name', 'description')
pass
class CategoryAdmin(admin.ModelAdmin):
list_display = ('name', 'parent')
class UnitePropertyAdmin(admin.ModelAdmin):
list_display = ('name', 'nature_unit', 'val_champ', 'val', 'val_unit')
#list_filter = ('name', 'val_champ', 'val', 'val_unit' )
ordering = ('-nature_unit',)
admin.site.register(Material, MaterialAdmin)
admin.site.register(Media2)
admin.site.register(Property, PropertyAdmin)
admin.site.register(MaterialProperty)
admin.site.register(Category, CategoryAdmin)
admin.site.register(UniteProperty, UnitePropertyAdmin)
category_list.html
{% extends "base.html" %}
{% load pagination_tags %}
{% block content %}
{% if object_list %}
<ul>
<hr>
<TT><font color="blue" size="2">Filtrage texte</font></TT>
<div>
<table width="10%" border="1" style="border: 0.5px;" cellspacing="0" cellpadding="0" >
<form action="{% url chercher %}" method="get">
<td><input type="text" name="q" id="q"/></td>
<td><input type="submit" value="valider "/></td>
</table>
</form>
</div>
<TT><font color="blue" size="2">Filtrage par critere</font></TT>
<div>
<table width="10%" border="1" style="border: 0.5px;" cellspacing="0" cellpadding="0" >
<form action="{% url chercher_filtre %}" method="get">
<td><input type="text" name="q"/></td>
<td><select name="fil" id="fil">
<option selected="selected" value="0">-- select --</option>
<option value="densite">densite</option>
<option value="rapport de poisson">rapport de poisson</option>
<option value="chaleur de fusion">chaleur de fusion</option>
<option value="durete Vickers">durete Vickers</option>
</select></td>
<td><input type="submit" value="valider"/></td>
</form>
</table>
</div>
<br/>
<p style=background-color:PowderBlue;><strong>Categories</strong></p>
<ul type=square>
{% for category in object_list %}
<li>
<a href="{{ category.get_absolute_url }}">{{ category }}</a>
{% if category.get_materiaux %}
{% with category.get_materiaux as mat_list %}
{% autopaginate mat_list 10 %}
{#<table border="1" width=50% style="border: 0.5px;">#}
<table style="background-color:white;" border=1 width=50%>
{% for mat in mat_list %}
<tr>
<td>
<a href="{{ mat.get_absolute_url }}"> {{ mat }} </a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</li>
{% paginate %}
{% endwith %}
<br/>
<a href="{% url record %}">Insertion donnees</a> | <a href="{% url nouveau %}">Nouveau materiau</a> |
<a href="{% url materiaux_category_root %}">Retour liste</a>
{% endif %}
{% endfor %}
</ul>
{% else %}
<table width=100%>
<tr bgcolor="abbba"><td colspan="30">
<font size="3" color="black">{{ category }}</font>
<h3> </h3>
<a href="{% url nouveau %}">Nouveau materiau</a> | <a href="{% url materiaux_category_root %}">Retour liste</a>
{% endif %}
{% endblock %}
material_detail.html
{% extends "base.html" %}
<body>
<div id="content">
{% block content %}
{% if object.get_physical_properties %}
<ul>
<TT> <strong><font size="4" color="black">Materiau : </font></strong><font size="4" color="red"> <strong>{{ object }}</strong></font></TT>
{% for prop in object.get_physical_properties|slice:":1" %}
<TT> {{ prop.name.description|linebreaks }}</TT>
{% endfor %}
{% for prop in object.get_physical_properties %}
{% ifchanged prop.nature_unit %} {# test unique sur le changement de propriete avec la precedente #}
<thead>
<p style=background-color:PowderBlue;> <TT><font size="4" color="black"><strong> {{prop.nature_unit}} </strong></font></TT></p>
</thead>
{% for media in object.get_medias %}
{% ifequal prop.nature_unit media.nature %} {# test l'egalite sur la propriete #}
{% ifequal media.get_format_display 'xls' %} {# detection du format de fichier #}
{# <a href="{{ media.source.url }}"> <img border=0 alt="" src="/projet_2/monprojet/image/8330.ico"/> </a> #}
{% endifequal %}
<a href="{{ media.source.url }}">{{ media.name }} {{ media.get_format_display }}</a>
{% endifequal %}
{% endfor %}
<table width="100%" border="1" style="border: 0.5px;" cellspacing="0" cellpadding="0" >
<div>
<tr bgcolor="dddddd">
<td width="150" <TT><strong>Propriete {{prop.nature_unit}} </strong></TT></td>
<td width="150" <TT><strong>SI </strong></TT></td>
<td width="150" <TT><strong>Unite</strong></TT></td>
</tr>
<tr>
<td width="150" <TT>{{ prop.val_champ}} </TT></td>
{% ifequal prop.val_champ 'densite' %}
<td width="150" <TT> <a href="{% url lit_param prop.id %}"> {{ prop.val }} </a></TT> </td> {# conversion unite #}
{#<td width="150" <TT> {{ prop.val }} </TT> </td> #}
{% else %}
<td width="150" <TT> {{ prop.val }}</TT> </td>
{% endifequal %}
<td width="150" <TT> {{ prop.val_unit }} </TT></td>
</tr>
</div>
</table>
{% else %}
<table width="100%" border="1" style="border: 0.5px;" cellspacing="0" cellpadding="0" >
<div>
<tr>
<td width="150" <TT>{{ prop.val_champ }} </TT></td>
<td width="150" <TT> {{ prop.val }}</TT> </td>
<td width="150" <TT> {{ prop.val_unit }} </TT></td>
</tr>
</div>
</table>
{% endifchanged %}
{% endfor %}
</ul>
<a href="javascript:history.go(-1)">Retour liste</a> |
<a href="{% url edition_media object.pk %}">Edition du formulaire medias </a> | <a href="{% url edition object.pk %}">Edition du formulaire </a> | <a href="{% url delete object.id %}">Supression du formulaire </a>
{% else %}
<font size="3" color="black">aucune donnee materiau...</font>
<a href="{% url edition object.pk %}">Edition du formulaire </a> | <a href="{% url delete object.id %}">Supression du formulaire </a> | <a href="javascript:history.go(-1)">Retour liste </a>
{#<a href="{% url record %}">Insertion donnees</a> | #}
{% endif %}
</div>
</body>
{% endblock %}
search_results.html
<p>Recherche du materiau : <strong>{{ query }}</strong></p>
{% if materiau %}
<ul>
{% for mater in materiau %}
<li><a href="{{ mater.get_absolute_url }}">{{ mater.name }}</li>
{% endfor %}
</ul>
{% else %}
<p>aucun materiau trouve suivant votre critere</p>
{% endif %}
<a href="{% url materiaux_category_root %}">Retour liste</a>
search_results_fit.html
<body>
<ul>
{% for mater2 in mat %}
{% if mater2.name in materiaux %}
<li>
<a href="{{ mater2.get_absolute_url }}"> {{ mater2.name }} </a>
</li>
{% endif %}
{% endfor %}
<br>
<p><TT> liste correspondante : </TT></p>
{% for mater in materiaux %}
<li>
<a href="{{ mater.get_absolute_url }}"> {{ mater.name }} </a>
</li>
{% endfor %}
</ul>
</body>
<a href="{% url materiaux_category_root %}">Retour liste</a>
manage_materiaux.html
{% extends "base.html" %}
{% block content %}
<form action="" method="POST">
{% csrf_token %}
<fieldset class="module aligned">
{% for field in materialform %}
<table>
<div class="form-row">
<div class="field-box">
<td> {{ field.label_tag }}: </td> <tr><td>{{ field }} </td></tr>
</div>
</div>
</table>
{% endfor %}
</fieldset>
<fieldset class="module aligned ">
<h2>Parametres</h2>
<table>
<tr>
{% for field in materialformset.forms.0 %}
{% if not field.is_hidden %}
<th>{{ field.label }}</th>
{% endif %}
{% endfor %}
</tr>
{% for f in materialformset.management_form %}
{{ f }}
{% endfor %}
{% for f in materialformset.forms %}
<tr>
{% for field in f %}
{% if not field.is_hidden %}
<td>
{{ field.errors }}
{{ field }}
</td>
{% else %}
<td valign="bottom">{{ field }}</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</table>
</fieldset>
<input type="submit" name="create" value="Modification" onclick="history.go(-1)">
</form>
<a href="javascript:history.go(-1)">Retour materiau</a>
{#<a href="{% url materiaux_category_root %}">Retour liste</a>#}
{% endblock %}
manage_media.html
{% extends "base.html" %}
{% block content %}
<form method="post" action="">
{% csrf_token %}
<fieldset class="module aligned ">
{% for field in materialform %}
<table>
<div class="form-row">
<div class="field-box">
<td> {{ field.label}} </td> <tr><td>{{ field }} </td></tr>
</div>
</div>
</table>
{% endfor %}
</fieldset>
<h2>Medias</h2>
<tr>
{% for field in materialformset.forms.0 %}
<div class="form-row">
<div class="field-box">
{% if not field.is_hidden %}
{# <th>{{ field.label }}</th> #}
{% endif %}
</div>
</div>
{% endfor %}
</tr>
{% for f in materialformset.management_form %}
{{ f }}
{% endfor %}
<fieldset class="module aligned ">
{% for f in materialformset.forms %}
<tr>
{% for field in f %}
<table>
<div class="form-row">
{% if not field.is_hidden %}
{{ field.errors }}
<td> {{ field.label }}: </td>
<tr><td>{{ field }} </td></tr>
{% else %}
<td valign="bottom">{{ field }}</td>
{% endif %}
</div>
</table>
{% endfor %}
</tr>
{% endfor %}
</fieldset>
<input type="submit" name="create" value="Modification" onclick="history.go(-1)">
</form>
<a href="javascript:history.go(-1)">Retour materiau</a>
{#{#<a href="{% url materiaux_category_root %}">Retour liste</a>#}
{% endblock %}
url.py (hors application)
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^', include('materiaux.urls')),
url(r'^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout'),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
urlpatterns += patterns('django.views.static',
url(r'^medias/(?P<path>.*)$', 'serve',
{'document_root': 'C:/projet_2/monprojet/medias'}),
)
setting.py
# Django settings for monprojet project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'monprojet.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/Paris'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'fr'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/projet_2/monprojet/medias/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = 'http://localhost:8000/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
#STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
#'django.contrib.staticfiles.finders.FileSystemFinder',
#'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = ')z1&zpasjl-o3_b*^+egxr#ek%q9$=et1e1kef!xje083zg6va'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.request',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'pagination.middleware.PaginationMiddleware',
)
ROOT_URLCONF = 'monprojet.urls'
import os.path
PROJECT_DIR = os.path.dirname(__file__)
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, "templates"),
#'C:/monprojet/materiaux/templates/materiaux/',
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
#'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'monprojet.materiaux',
#'django_extensions',
'mptt',
'pagination',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment