# Path: examples/django_qrcode/qrcode/models.py
# class Ticket(models.Model):
#     """Example which stores an alphanumeric name and the name as QR code.
#     """
#     name = models.CharField(max_length=150, unique=True)
#     qrcode = models.ImageField(upload_to='ticket-qrcodes/')
# 
# Path: examples/django_qrcode/qrcode/forms.py
# class TicketForm(forms.Form):
#     """Simple form for the Ticket model."""
#     name = forms.CharField(label='Name', max_length=150, min_length=1,
#                            validators=[RegexValidator(r'^[A-Z0-9]+$')])


import io
import segno
from django.http import HttpResponse, HttpResponseRedirect
from django.core.files.base import ContentFile
from django.shortcuts import render
from .models import Ticket
from .forms import TicketForm


def index(request):
    """Renders the form to create a ticket"""
    if request.method == 'POST':
        form = TicketForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            qr = segno.make_qr(name)
            buff = io.BytesIO()
            qr.save(buff, kind='png', scale=3, dark='darkblue')
            ticket = Ticket(name=name)
            ticket.qrcode.save(name + '.png', ContentFile(buff.getvalue()),
                               save=True)
            return HttpResponseRedirect('/thanks/')
    else:

# Path: examples/django_qrcode/qrcode/models.py
# class Ticket(models.Model):
#     """Example which stores an alphanumeric name and the name as QR code.
#     """
#     name = models.CharField(max_length=150, unique=True)
#     qrcode = models.ImageField(upload_to='ticket-qrcodes/')
# 
# Path: examples/django_qrcode/qrcode/forms.py
# class TicketForm(forms.Form):
#     """Simple form for the Ticket model."""
#     name = forms.CharField(label='Name', max_length=150, min_length=1,
#                            validators=[RegexValidator(r'^[A-Z0-9]+$')])


# Path: examples/django_qrcode/qrcode/views.py
import io
import segno
from django.http import HttpResponse, HttpResponseRedirect
from django.core.files.base import ContentFile
from django.shortcuts import render
from .models import Ticket
from .forms import TicketForm



def index(request):
    """Renders the form to create a ticket"""
    if request.method == 'POST':
        form = TicketForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            qr = segno.make_qr(name)
            buff = io.BytesIO()
            qr.save(buff, kind='png', scale=3, dark='darkblue')
            ticket = Ticket(name=name)
            ticket.qrcode.save(name + '.png', ContentFile(buff.getvalue()),
                               save=True)
            return HttpResponseRedirect('/thanks/')
    else:

        form = TicketForm()