示例#1
0
 def test_no_form_errors(self):
     """
     Test that submitting a form with all fields correctly filled does not
     return any errors.
     """
     form_data = {'all_emails': '*****@*****.**',
                  'city': 'Chicago',
                  'first_name': 'Jane',
                  'last_name': 'Doe',
                  'phone': '1234567890',
                  'state': 'IL',
                  'street_address': '1 North St.'}
     eu_form = CustomerForm(data=form_data)
     eu_form.is_valid()  # attempt to validate to get errors
     correct_errors = {}
     self.assertEqual(eu_form._errors, correct_errors)
示例#2
0
 def test_empty_form_errors(self):
     """
     Test that submitting empty form returns 'this field required' errors
     for every field.
     """
     form_data = {}
     eu_form = CustomerForm(data=form_data)
     eu_form.is_valid()  # attempt to validate to get errors
     correct_errors = {'all_emails': [u'This field is required.'],
                       'city': [u'This field is required.'],
                       'first_name': [u'This field is required.'],
                       'last_name': [u'This field is required.'],
                       'phone': [u'This field is required.'],
                       'state': [u'This field is required.'],
                       'street_address': [u'This field is required.']}
     self.assertEqual(eu_form._errors, correct_errors)
示例#3
0
def signup(request):
    """ Display and process sign up form.
    """

    if request.method == 'POST':   # if form is being submitted
        eu_form = CustomerForm(request.POST)
        if eu_form.is_valid():
            eu_form.save()
            # Parse out the email addresses from text field input, and save
            # them as CustomerEmail instances, each with a FK to its Customer.
            emails_string = eu_form.cleaned_data['all_emails']
            emails = parse_emails(emails_string)
            customer = Customer.objects.latest('id')
            # save each email as an CustomerEmail instance
            for email in emails:
                email = CustomerEmail(email=email, customer=customer)
                email.save()
            messages.success(request, 'submit_success')
            # clear form
            eu_form = CustomerForm()
            return HttpResponseRedirect(request.path)
    else:  # viewing form, not submitting
        eu_form = CustomerForm()
    return render_to_response('signup.html',
                              {'eu_form': eu_form },
                              context_instance=RequestContext(request)
                             )
示例#4
0
 def test_cant_submit_empty_form(self):
     """
     Test that an empty form does not validate.
     """
     form_data = {}  # empty
     eu_form = CustomerForm(data=form_data)
     self.assertEqual(eu_form.is_valid(), False)
示例#5
0
 def test_clean(self):
     """ Test that if the Emails ('all_emails') field does not contain at
     least one valid email address, the correct error is returned.
     """
     form_data = {'all_emails': 'asldjflsdkjf',
                  'city': 'Chicago',
                  'first_name': 'Jane',
                  'last_name': 'Doe',
                  'phone': '1234567890',
                  'state': 'IL',
                  'street_address': '1 North St.'}
     eu_form = CustomerForm(data=form_data)
     eu_form.is_valid()  # attempt to validate to get errors
     corr_error = eu_form.error_class(
         ['Please enter at least one valid email address']
     )
     self.assertEqual(eu_form._errors['all_emails'], corr_error)
示例#6
0
    def post(self, request):
        form = CustomerForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('customer')

        args = {'form': form, 'title': text, 'posts': posts}
        return render(request, self.template_name, args)
示例#7
0
    def test_can_submit_correct_form(self):
        """
        Test that correct form validates.
        """
        form_data = {'all_emails': '*****@*****.**',
                     'city': 'Chicago',
                     'first_name': 'Jane',
                     'last_name': 'Doe',
                     'phone': '1234567890',
                     'state': 'IL',
                     'street_address': '1 North St.'}
        eu_form = CustomerForm(data=form_data)

        self.assertEqual(eu_form.is_valid(), True)
示例#8
0
def edit_view(request):
    c = tools.get_default_context(request, 'm_edit')
    if request.method == 'POST':  # If the form has been submitted...
        # A form bound to the POST data and instance
        form = CustomerForm(request.POST, instance=Customer.objects.all()[0])
        if form.is_valid():
            form.save()  # Saving form to model
            # Is that Ajax?
            if request.is_ajax():
                return HttpResponse("Data stored successfuly!")
            return HttpResponseRedirect('/')  # Redirect after POST
    else:
        customer = Customer.objects.all()[0]
        form = CustomerForm(instance=customer)  # An unbound form

    c['form'] = form
    return render_to_response('edit.html', c,
                              context_instance=RequestContext(request))
示例#9
0
    def post(self, request):
        edit = request.GET.get("edit")

        if edit:
            c = Customer.objects.get(id62=edit)
            c_form = CustomerForm(request.POST, instance=c)
            u_form = UserForm(request.POST, instance=User.objects.get(id=c.created_by_id))
        else:
            c_form = CustomerForm(request.POST)
            u_form = UserForm(request.POST)

        if u_form.is_valid():
            user = u_form.save(commit=False)
            user.date_joined = datetime.now()
            user.set_password(request.POST.get("password"))
            user.is_staff = False
            user.is_active = True

            if c_form.is_valid():
                user.save()                
                customer = c_form.save(commit=False)
                if edit:
                    customer.updated_by = request.user
                else:
                    customer.created_by = user
                customer.save()

                messages.success(request, 'Customer (%s %s) has been saved.' % (user.first_name, user.last_name))
                
                return redirect(
                    reverse("app:customer")
                )
            else:
                print c_form.errors
        else:
            print u_form.errors

        return self.render_to_response({"form":{'user':u_form, 'customer':c_form}})
示例#10
0
def startInvoice(request, template_name='app/startInvoice.html'):
    form1 = CustomerForm(request.POST or None)
    form2 = InvoiceForm(request.POST or None)
    form3 = InvoiceItemsForm()
    data = {
        "startInvoice": "active",
        'title': 'Invoice',
        'year': datetime.now().year,
        'form1': form1,
        'form2': form2,
        'form3': form3
    }

    if form1.is_valid() and form2.is_valid():
        invoice = form2.save()

        customerID = int(request.POST.get('customerID'))
        if customerID == 0:
            customer = form1.save()
            invoice.customer_id = customer.id
        else:
            invoice.customer_id = customerID

        invoiceNo = str(invoice.id).zfill(4)
        invoice.invoiceNo = 'UM' + invoiceNo
        if invoice.balance == 0:
            invoice.status = True
        else:
            invoice.status = False
        invoice.save()

        part = request.POST.getlist('itemID[]')
        part_name = request.POST.getlist('itemName[]')
        price = request.POST.getlist('salePrice[]')
        quantity = request.POST.getlist('quantity[]')
        amount = request.POST.getlist('amount[]')
        itemType = request.POST.getlist('itemType[]')

        # FIXME: number of each field should equal
        c = min([
            len(part),
            len(part_name),
            len(price),
            len(quantity),
            len(amount)
        ])
        for i in range(c):
            # create a form instance and populate it with data from the request:
            form3 = InvoiceItemsForm({
                'part': part[i],
                'part_name': part_name[i],
                'price': price[i],
                'quantity': quantity[i],
                'amount': amount[i],
                'itemType': itemType[i]
            })
            invoiceItems = form3.save()
            invoiceItems.invoice_id = invoice.id
            invoiceItems.save()

            if itemType[i] == '1':
                partObj = get_object_or_404(Part, pk=int(part[i]))
                if partObj.stock - int(quantity[i]) > 0:
                    partObj.stock = partObj.stock - int(quantity[i])
                else:
                    partObj.stock = 0
                partObj.save()

        return redirect('invoice', invoice.id)

    return render(request, template_name, data)
示例#11
0
def book(request, booking):
    """Allows a user to create an event. The event is not confirmed and will only display on the book page. The customer is created along with the booking."""
    bookingType = booking
    data = dict()
    assert isinstance(request, HttpRequest)

    if request.method == 'POST':

        form = EventForm(venue=Venue.VENUE_TYPE_MAP[booking],
                         data=request.POST)
        customerForm = CustomerForm(request.POST)
        if all([form.is_valid(), customerForm.is_valid()]):
            customer = customerForm.save()
            event = form.save(commit=False)
            event.customer = customer
            event.created = timezone.now()
            event.save()
            #contact venue with the event details
            contact_venue_on_booking(event, customer, request)
            contact_customer_on_booking(event, customer)
            data['form_is_valid'] = True
        else:
            data['form_is_valid'] = False
    else:
        form = EventForm(venue=Venue.VENUE_TYPE_MAP[booking])
        customerForm = CustomerForm()

    allEvents = []
    allVenues = []
    allColors = []
    #filter dates today or later
    today = timezone.now()
    venues = Venue.objects.filter(venue_type=Venue.VENUE_TYPE_MAP[booking])
    for currentVenue in venues:
        #get all events for each venue type
        #annotate will rename 'venue__color' to 'color
        packages = Event.objects.annotate(
            color=F('venue__color'),
            editable=F('confirmed'),
            type=F('event_type')).filter(venue=currentVenue.id).filter(
                start__gte=today).all().values('id', 'title', 'start',
                                               'venue__name',
                                               'venue__venue_type', 'type',
                                               'color', 'editable')
        if packages.exists():
            eventGroup = []
            for package in packages:
                package['editable'] = not package['editable']  #flip the value
                package['type'] = Event.EVENT_TYPES[package['type'] - 1][
                    1]  #event type for details popup
                package['start'] = normalize(
                    package['start'])  #convert UTC time to eastern
                if package['editable'] == True:
                    package['borderColor'] = "red"
                    package['title'] = "Tentative"
                eventGroup.append(package)
                #store list of all distinct venues for choicespartial
                if (currentVenue.id, package['venue__name']) not in allVenues:
                    allVenues.append((currentVenue.id, package['venue__name']))
                    allColors.append(currentVenue.color)
            json_obj = dict(events=eventGroup)
            allEvents.append(json_obj)
    zipData = zip(
        allVenues,
        allColors)  #zip the event types and colors together for template
    if request.method == 'GET':
        return render(
            request, 'app/book.html', {
                'form': EventForm(venue=Venue.VENUE_TYPE_MAP[booking]),
                'customerForm': CustomerForm(),
                'editDateForm': EditDateForm(),
                'events': json.dumps(allEvents, default=str),
                'title': 'Book',
                'year': datetime.now().year,
                'booking': bookingType,
                'extra_context': zipData
            })
    elif request.method == 'POST':
        context = {'form': form, 'customerForm': customerForm}
        data['html_form'] = render_to_string('app/partial_book_create.html',
                                             context,
                                             request=request)
        data['updated_events'] = json.dumps(allEvents, default=str)
        return JsonResponse(data)