Permalink
Browse files

work on orders - start on forms

  • Loading branch information...
1 parent a6a5343 commit fff9de585e214ee6defe1f27a49a840de17867eb @Guest007 committed Feb 7, 2014
View
@@ -7,7 +7,7 @@
def prod(request):
production = Article.objects.get(category__slug='prod')
context = {'prod': production}
- return render(request, 'article.html', context)
+ return render(request, 'prod.html', context)
def clients(request):
View
@@ -2,11 +2,13 @@
from eurocard import settings
from articles import views
+from orders import views as orders
from django.conf.urls.static import static
from django.contrib import admin
import grappelli
from filebrowser.sites import site
+from orders.views import save_order
admin.autodiscover()
@@ -20,6 +22,12 @@
url(r'^price/', views.price, name='price'),
url(r'^cooperation/', views.cooperation, name='cooperation'),
url(r'^contacts/', views.contacts, name='contacts'),
+ url(r'^test/', orders.home, name='t_order'),
+ # Ajax actions
+ url(r"^second/(?P<pk>\d+)/$", orders.nextstep_order, name="ajax-nextstep-order"),
+ url(r"^(?P<pk>\d+)/(?P<step>\d+)/$", orders.edit_order, name="edit-order"),
+ url(r"^(?P<pk>\d+)/$", orders.edit_order, name="edit-order"),
+ url(r"^save/ajax/(?P<step>\d+)/$", orders.save_order, name="ajax-save-order"),
url(r'^grappelli/', include('grappelli.urls')),
View
@@ -52,8 +52,8 @@ class OrdersAdmin(admin.ModelAdmin):
class OrderTemplateAdmin(admin.ModelAdmin):
model = OrderTemplate
- list_display = ['name', 'is_template', 'image']
- # ordering = ["category", 'published_at']
+ list_display = ['name', 'is_template', 'price']
+ ordering = ["name", 'is_template', 'price']
list_filter = ['name', 'is_template']
View
@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+from django import forms
+from orders.models import OrderTemplate, Orders, Material, Lamination, Color
+from django.forms.formsets import formset_factory
+
+class TemplOrderForm(forms.ModelForm):
+ barcode = forms.BooleanField()
+
+ class Meta:
+ model = OrderTemplate
+ fields = ['name', 'is_template', 'price', 'barcode']
+
+# TOrderFormSet = formset_factory(TemplOrderForm)
+
+
+class OrderForm(forms.ModelForm):
+ # name = forms.CharField(verbose_name="Наименование")
+ # description = forms.CharField(verbose_name="Описание")
+ # constant boolean fields
+ # is_template = forms.BooleanField(verbose_name="Это заготовка?")
+ chip = forms.BooleanField()
+ scratch = forms.BooleanField()
+ magnet = forms.BooleanField()
+ emboss = forms.BooleanField()
+ uv = forms.BooleanField()
+ print_num = forms.BooleanField()
+ sign = forms.BooleanField()
+ foil = forms.BooleanField()
+ barcode = forms.BooleanField()
+ indent = forms.BooleanField()
+ # price = forms.FloatField()
+
+ # related fields
+ material = forms.ModelChoiceField(queryset=Material.objects.all())
+ lamination = forms.ModelChoiceField(queryset=Lamination.objects.all())
+ color_front = forms.ModelChoiceField(queryset=Color.objects.all())
+ color_back = forms.ModelChoiceField(queryset=Color.objects.all())
+ # load file
+ # image = forms.ImageField(upload_to="card/", blank=True, null=True, verbose_name="Образец")
+
+ class Meta:
+ model = Orders
+ # fields = ['draw']
+
View
@@ -52,27 +52,42 @@ def __unicode__(self):
return self.name
+class Modificators(models.Model):
+ name = models.CharField(max_length=255, verbose_name="Наименование")
+ value = models.BooleanField(default=False, verbose_name="Значение")
+ cost = models.FloatField(blank=True, null=True, verbose_name="Стоимость модификатора")
+
+ class Meta:
+ verbose_name = "Модификатор"
+ verbose_name_plural = "Модификаторы"
+
+ def __unicode__(self):
+ return self.name
+
+
class OrderTemplate(models.Model):
# constant fields
- name = models.CharField(max_length=100, verbose_name="Наименование")
- description = models.CharField(max_length=255, verbose_name="Описание")
+ name = models.CharField(blank=True, null=True, max_length=100, verbose_name="Наименование")
+ description = models.CharField(blank=True, null=True, max_length=255, verbose_name="Описание")
# constant boolean fields
- is_template = models.BooleanField(verbose_name="Это заготовка?")
- chip = models.BooleanField(verbose_name="карта с чипом")
- scratch = models.BooleanField(verbose_name="стираемая полоса")
- magnet = models.BooleanField(verbose_name="магнитная полоса")
- emboss = models.BooleanField(verbose_name="эмбоссирование")
- uv = models.BooleanField(verbose_name="печать УФ краской")
- print_num = models.BooleanField(verbose_name="печать номера")
- sign = models.BooleanField(verbose_name="полоса для подписи")
- foil = models.BooleanField(verbose_name="тиснение фольгой")
- barcode = models.BooleanField(verbose_name="печать штрих-кода")
- indent = models.BooleanField(verbose_name="идентная печать")
+ is_template = models.BooleanField(default=False, verbose_name="Это заготовка?")
+ chip = models.BooleanField(default=False, verbose_name="карта с чипом")
+ scratch = models.BooleanField(default=False, verbose_name="стираемая полоса")
+ magnet = models.BooleanField(default=False, verbose_name="магнитная полоса")
+ emboss = models.BooleanField(default=False, verbose_name="эмбоссирование")
+ uv = models.BooleanField(default=False, verbose_name="печать УФ краской")
+ print_num = models.BooleanField(default=False, verbose_name="печать номера")
+ sign = models.BooleanField(default=False, verbose_name="полоса для подписи")
+ foil = models.BooleanField(default=False, verbose_name="тиснение фольгой")
+ barcode = models.BooleanField(default=False, verbose_name="печать штрих-кода")
+ indent = models.BooleanField(default=False, verbose_name="идентная печать")
+ price = models.FloatField(blank=True, null=True, verbose_name="Цена за штуку")
+
# related fields
- material = models.ForeignKey(Material, verbose_name="Материал")
- lamination = models.ForeignKey(Lamination, verbose_name="Вид ламинации")
- color_front = models.ForeignKey(Color, related_name="color_front", verbose_name="Количество цветов на лицевой стороне")
- color_back = models.ForeignKey(Color, related_name="color_back", verbose_name="на обороте")
+ material = models.ForeignKey(Material, blank=True, null=True, verbose_name="Материал")
+ lamination = models.ForeignKey(Lamination, blank=True, null=True, verbose_name="Вид ламинации")
+ color_front = models.ForeignKey(Color, blank=True, null=True, related_name="color_front", verbose_name="Количество цветов на лицевой стороне")
+ color_back = models.ForeignKey(Color, blank=True, null=True, related_name="color_back", verbose_name="на обороте")
# load file
image = models.ImageField(upload_to="card/", blank=True, null=True, verbose_name="Образец")
@@ -86,15 +101,15 @@ def __unicode__(self):
class Orders(models.Model):
# constant fields
- FIO = models.CharField(max_length=255, verbose_name="ФИО")
- phone = models.CharField(max_length=255, verbose_name="Телефон")
- email = models.EmailField(verbose_name="E-mail")
- draw = models.IntegerField(default=1000, verbose_name="Тираж")
- cost = models.FloatField(blank=True, null=True, verbose_name="Стоимость за заказа")
+ FIO = models.CharField(blank=True, null=True, max_length=255, verbose_name="ФИО")
+ phone = models.CharField(blank=True, null=True, max_length=255, verbose_name="Телефон")
+ email = models.EmailField(blank=True, null=True, verbose_name="E-mail")
+ draw = models.IntegerField(default=500, verbose_name="Тираж")
+ cost = models.FloatField(blank=True, null=True, default=0, verbose_name="Стоимость заказа")
# load file
maket = models.FileField(upload_to="maket/", blank=True, null=True, verbose_name="Мой макет (если есть)")
# related fields
- template = models.ForeignKey(OrderTemplate, unique=True, verbose_name="Болванка заказа")
+ template = models.ForeignKey(OrderTemplate, blank=True, null=True, unique=True, verbose_name="Болванка заказа")
class Meta:
verbose_name = "Заказ"
No changes.
View
@@ -1,3 +1,138 @@
-from django.shortcuts import render
+# -*- coding: utf-8 -*-
+from annoying.functions import get_object_or_None
+from annoying.decorators import render_to
+from django.core.urlresolvers import reverse
+from django.shortcuts import render, get_object_or_404
+from django.shortcuts import render_to_response
+from django.template import RequestContext
+from orders.models import OrderTemplate, Orders, Material, Lamination, Color
+import json
+from django.views.decorators.csrf import csrf_exempt, csrf_protect
+from django import http
+
+__author__ = 'guest007'
+
+
+def home(request):
+ template_name = 'home1.html'
+ return render_to_response(template_name,
+ {'draw': '500',
+ 'materials': Material.objects.all(),
+ 'lamination': Lamination.objects.all(),
+ 'color_front': Color.objects.all().order_by('-id'),
+ 'color_back': Color.objects.all().order_by('-id')},
+ context_instance=RequestContext(request))
+
+
+@render_to()
+def edit_order(request, pk, step=0):
+ """Edit selected Order"""
+ if step == 0:
+ return http.HttpResponseRedirect('1/')
+ order = get_object_or_404(Orders, pk=int(pk))
+ templ = OrderTemplate.objects.get(id=order.template.id)
+ return {"TEMPLATE": 'home1.html',
+ "object": order,
+ "templ": templ,
+ 'materials': Material.objects.all(),
+ 'lamination': Lamination.objects.all(),
+ 'color_front': Color.objects.all().order_by('-id'),
+ 'color_back': Color.objects.all().order_by('-id')}
+
+
+# @render_to()
+def nextstep_order(request, pk):
+ """Final confirm of Order"""
+ print "pk: ", pk
+ order = get_object_or_404(Orders, pk=int(pk))
+ templ = OrderTemplate.objects.get(id=order.template.id)
+ result = {"object": order,
+ "templ": templ,
+ 'material': Material.objects.get(id=templ.material),
+ 'lamination': Lamination.objects.get(id=templ.lamination),
+ 'color_front': Color.objects.get(id=templ.color_front),
+ 'color_back': Color.objects.get(id=templ.color_back)}
+ return render_to_response('helpers.html', result,
+ mimetype="application/xhtml+xml")
+
+
+@csrf_protect
+def save_order(request, step=1):
+ """Save order with AJAX"""
+ if request.method != "POST":
+ result = {"result": "ERROR", "msg": "Wrong request method"}
+ return http.HttpResponse(json.dumps(result),
+ content_type="application/json")
+ try:
+ templ_id = int(request.POST.get("templ_id", 0)) # Если редактруем созданный заказ
+ except (TypeError, ValueError):
+ templ_id = 0
+
+ user = request.POST.get("user", None)
+ phone = request.POST.get("phone", None)
+ email = request.POST.get("email", None)
+
+ templ = get_object_or_None(OrderTemplate, pk=templ_id) # Или получаем тело заказа или создаём новое (новый заказ)
+
+ if templ is None:
+ templ = OrderTemplate(name=(user if user else '')) # Создаем тело заказа. Название - имя заказчика
+
+ templ.material = Material(id=request.POST.get("materials", None))
+ templ.color_back = Color(id=request.POST.get("color_back", None))
+ templ.color_front = Color(id=request.POST.get("color_front", None))
+ templ.lamination = Lamination(id=request.POST.get("lamination", None))
+ templ.chip = request.POST.get("chip", False)
+ templ.uv = request.POST.get("uv", False)
+ templ.magnet = request.POST.get("magnet", False)
+ templ.emboss = request.POST.get("emboss", False)
+ templ.scratch = request.POST.get("scratch", False)
+ templ.print_num = request.POST.get("print_num", False)
+ templ.sign = request.POST.get("sign", False)
+ templ.indent = request.POST.get("indent", False)
+ templ.barcode = request.POST.get("barcode", False)
+ templ.foil = request.POST.get("foil", False)
+
+ draw = request.POST.get("draw", '500') # количество в заказ
+
+ templ.save() # Сохраняем тело заказа для того, чтобы потом создать сам заказ
+ if templ is None: # Если тело заказа не сохранилось - возвращаем ошибку?
+ result = {"result": "ERROR", "msg": "Please, correct the property type to get access to other tabs."}
+ return http.HttpResponse(json.dumps(result),
+ content_type="application/json")
+
+ try: # Проверяем, это новый заказ или редактируем созданный
+ pk = int(request.POST.get("id", 0))
+ print "ID of Order: ", pk
+ except (TypeError, ValueError):
+ pk = 0
+ order = None
+ if pk not in (None, 0):
+ # Search existed objects
+ order = get_object_or_None(Orders, pk=pk)
+ if order is None:
+ # Create new object
+ order = Orders()
+
+ order.template = OrderTemplate(id=templ.id)
+ order.FIO = user
+ order.draw = draw # Количество
+ order.cost = 0 # TODO: Пока просто пишем 0. ИСПРАВИТЬ!!!!
+ order.email = email
+ order.phone = phone
+ # order.maket = '' # TODO: Пока ничего не пишем. ИСПРАВИТЬ!!!
+
+ order.save()
+ print "ID of Order (order.id): ", order.id
+
+ if step == '1':
+ result = {"result": "OK", "id": order.id,
+ "msg": "Changes are saved. Don't forget to publish your advertisement!",
+ "url": reverse("edit-order", args=[order.id, 3])}
+ return http.HttpResponse(json.dumps(result),
+ content_type="application/json")
+ else:
+ result = {"result": "OK", "id": order.id, "msg": "This case 'else'",
+ "url": reverse("edit-order", args=[order.id, step])}
+ return http.HttpResponse(json.dumps(result),
+ content_type="application/json")
-# Create your views here.
View
@@ -5,3 +5,4 @@ pillow
django-filebrowser
django-debug-toolbar
django-menu
+django-annoying==0.7.7
View
@@ -31,12 +31,12 @@
<a href="#" class="prev"><i class="fa fa-angle-left"></i></a>
<a href="#" class="next"><i class="fa fa-angle-right"></i></a>
<div class="carousel">
- <div class="item" style="background: url('/static/images/demo/marko.jpg') no-repeat center center / cover"></div>
- <div class="item" style="background: url('/static/images/demo/pissofart_1.jpg') no-repeat center center / cover"></div>
- <div class="item" style="background: url('/static/images/demo/rojo_nova.jpg') no-repeat center center / cover"></div>
- <div class="item" style="background: url('/static/images/demo/pissofart_1.jpg') no-repeat center center / cover"></div>
- <div class="item" style="background: url('/static/images/demo/marko.jpg') no-repeat center center / cover"></div>
- <div class="item" style="background: url('/static/images/demo/rojo_nova.jpg') no-repeat center center / cover"></div>
+ <div class="item" style="background: url('{{ STATIC_URL }}images/demo/marko.jpg') no-repeat center center / cover"></div>
+ <div class="item" style="background: url('{{ STATIC_URL }}images/demo/pissofart_1.jpg') no-repeat center center / cover"></div>
+ <div class="item" style="background: url('{{ STATIC_URL }}images/demo/rojo_nova.jpg') no-repeat center center / cover"></div>
+ <div class="item" style="background: url('{{ STATIC_URL }}images/demo/pissofart_1.jpg') no-repeat center center / cover"></div>
+ <div class="item" style="background: url('{{ STATIC_URL }}images/demo/marko.jpg') no-repeat center center / cover"></div>
+ <div class="item" style="background: url('{{ STATIC_URL }}images/demo/rojo_nova.jpg') no-repeat center center / cover"></div>
</div>
</div>
{{ about.content|safe }}
@@ -82,3 +82,6 @@
{% block our_clients %}
{% endblock %}
+
+{% block benefits %}
+{% endblock %}
Oops, something went wrong.

0 comments on commit fff9de5

Please sign in to comment.