def _handler(self, account_slug, customer_slug, post=False): user = users.get_current_user() if user: account = Account.all()\ .filter('user ='******'slug =', account_slug).get() customer = Customer.all()\ .filter('account =', account).filter('slug =', customer_slug).get() if post: form = CustomerForm(instance=customer, data=self.request.POST) if form.is_valid(): # Save the data, and redirect to the view page form.save() self.redirect(account.get_absolute_url()) else: form = CustomerForm(instance=customer) path = os.path.join(os.path.dirname(__file__), 'templates/customer_details.html') self.response.out.write(template.render(path, { 'account': account, 'customer': customer, 'form': form, 'user': user, 'logout_url': users.create_logout_url("/") })) else: self.redirect(users.create_login_url(self.request.uri))
def customer_register(request): customer_form = CustomerForm(request.POST) if customer_form.is_valid(): customer.create(customer_form) verify_code_model = request.verify_code_meta['verify_code_model'] verify_code_model.delete() return json_response_from_object(OK, CODE_MESSAGE.get(OK)) else: return json_response(PARAM_REQUIRED, customer_form.errors)
def addcustomer(): form = CustomerForm() if form.validate_on_submit(): customer = Customer(name = form.name.data, user = g.user.id) db.session.add(customer) db.session.commit() flash('customer rajoute') return redirect(url_for('addcustomer')) return render_template('customer.html',form = form)
def customer_create(): form = CustomerForm(request.form) if form.validate_on_submit(): customer = Customer(phone=form.phone.data, email=form.email.data, name=form.name.data) return redirect('/') return render_template('customer/create.html', form=form)
def customer_add(request): if request.method == 'POST': form = CustomerForm(request.POST) if form.is_valid(): c = form.save(commit=False) c.sn = generate_sn(prefix = 'CTM') c.save() serializer = JSONSimpleSerializer() return HttpResponse(serializer.serialize([c,])) else: form = CustomerForm() return render_to_response('modal/main_form.html',{'action':'Add', 'module':module, 'form': form},context_instance=RequestContext(request))
def customer_add(): form = CustomerForm(request.form) if request.method == 'POST' and form.validate(): new_user = Customer(name=form.name.data, email=form.email.data, tel=form.tel.data) db.session.add(new_user) db.session.commit() flash('Başarılı bir şekilde müşteri eklediniz', 'success') return redirect(url_for('customer_add')) else: return render_template('customer_add.html', form=form)
def customer_register(request): customer_form = CustomerForm(request.POST) if customer_form.is_valid(): customer_dict = customer_form.cleaned_data if customer.isUnregistered(customer_dict['user_name']): customer.create(customer_dict) verify_code_model = request.verify_code_meta['verify_code_model'] verify_code_model.delete() return json_response_from_object(OK, CODE_MESSAGE.get(OK)) else: return json_response(USER_REGISTERED, CODE_MESSAGE.get(USER_REGISTERED)) else: return json_response(PARAM_REQUIRED, customer_form.errors)
def customer_update(request): if request.method == 'POST': postdata = request.POST.copy() try: c = Customer.objects.get(sn=postdata.pop('sn')[0]) except Customer.DoesNotExist: raise Http404(module + ' not found') form = CustomerForm(postdata, instance=c) if form.is_valid(): c_saved = form.save() serializer = JSONSimpleSerializer() return HttpResponse(serializer.serialize([c_saved,])) else: return HttpResponse('Invalid request.')
def edit(id): qry = db.session.query(customer).filter(customer.id == id) customer_info = qry.first() if customer_info: form = CustomerForm(formdata=request.form, obj=customer_info) if request.method == 'POST' and form.validate(): # save edits save_changes(customer_info, form) flash('Cliente registrado!') return redirect('/') return render_template('edit_customer.html', form=form) else: return 'Error loading #{id}'.format(id=id)
def new_customer(): """ Add a new customer """ form = CustomerForm(request.form) if request.method == 'POST' and form.validate(): # save the album new_customer = customer() save_changes(new_customer, form, new=True) flash('Cliente Registrado!') return redirect('/') return render_template('new_customer.html', form=form)
def edit(request, id): customer = get_object_or_404(Customer, id=id) if request.method == 'POST': form = CustomerForm(request.POST, instance=customer) form_valid = form.is_valid() if form_valid: customer = form.save() customer.full_name = request.POST.get('name') + ' ' + request.POST.get('last_name') customer.save() return HttpResponseRedirect(reverse(mycustomers)) else: form = CustomerForm(instance=customer) return render_to_response('customers/edit.html', locals(), context_instance=RequestContext(request))
def showedit_customer(c_id): form = CustomerForm(request.form, session.query(Customer).get(c_id)) return render_template('customer_form.html', form=form, method="POST", action="/customers/%s/edit" % c_id, submit_text="Save changes")
def _add_customers(): form = CustomerForm(request.form) return render_template('customer_form.html', form=form, method="POST", action="/add", error=None, submit_text="Save")
def customer(id): customer = Customer.query.get(id) if request.method == 'DELETE': db.session.delete(customer) db.session.commit() return redirect(url_for('customers')) else: form = CustomerForm(request.form) if form.validate(): form.populate_obj(customer) db.session.add(customer) db.session.commit() return redirect(url_for('customers')) else: return render_template('edit_customer.html', form=form, customer=customer)
def add_customers(): form = CustomerForm(request.form) error = None if form.validate(): customer = Customer(form.first_name.data, form.last_name.data, form.email.data, form.age.data) flash('You sucessfully added a new customer!') session.add(customer) session.commit() return redirect(url_for('customers')) else: error = "Fields are not filled correctly!" return render_template('customer_form.html', form=form, method="POST", action="/add", error=error, submit_text="Save")
def profile(request, template='accounts/account_profile.html'): #print BaseUser.objects.all() #print request.user.pk #print request.user.username u = User.objects.get(id=request.user.pk) print u.groups.all() #base_user = get_object_or_404(BaseUser, user_id=request.user.pk) #print base_user print request.user.pk print request.user.username print request.user.groups.all() groups = request.user.groups.values_list('name', flat=True) print groups def update_user(user, form): for k, v in form.cleaned_data.items(): print k, v setattr(user, k, v) #agent.password = form.cleaned_data.get('password') #agent.phone = form.cleaned_data.get("phone") user.save() u.email = user.email from django.contrib.auth.hashers import (check_password, make_password, is_password_usable) u.password = make_password(user.password) u.save() if 'AgentGroup' in groups: agent = get_object_or_404(Agent, username=request.user.username) #form = AgentForm(request.POST or None, initial={'username': agent.username, 'phone': agent.phone}) form = AgentForm(request.POST or None, instance=agent) if request.method == "POST" and form.is_valid(): update_user(agent, form) info(request, _("Agent updated")) context = {"form": form, "title": _("Update Agent")} return render(request, template, context) elif 'CustomerGroup' in groups: customer = get_object_or_404(Customer, username=request.user.username) form = CustomerForm(request.POST or None, instance=customer) if request.method == "POST" and form.is_valid(): update_user(customer, form) info(request, _("Customer updated")) context = {"form": form, "title": _("Update Customer")} return render(request, template, context) elif 'SuperAdminGroup' in groups or 'AdminGroup' in groups: admin = get_object_or_404(SysAdmin, username=request.user.username) form = SysAdminForm(request.POST or None, instance=admin) if request.method == "POST" and form.is_valid(): update_user(admin, form) #TODO change group if necessary info(request, _("SysAdmin updated")) context = {"form": form, "title": _("Update SysAdmin")} return render(request, template, context) return render(request, template)
def edit_customer(c_id): form = CustomerForm(request.form) if form.validate(): cust_edited = Customer(form.first_name.data, form.last_name.data, form.email.data, form.age.data) flash('You sucessfully edited customer') customer_db = session.query(Customer).get(c_id) customer_db.first_name = cust_edited.first_name customer_db.last_name = cust_edited.last_name customer_db.age = cust_edited.age customer_db.email = cust_edited.email session.commit() return redirect(url_for('customers')) else: error = "Fields are not filled correctly!" return render_template('customer_form.html', form=form, method="POST", action="/customer/%s/edit" % c_id, submit_text="Save changes")
def delete(id): """ Delete the item in the database that matches the specified id in the URL """ qry = db.session.query(customer).filter(customer.id == id) customer_info = qry.first() if customer: form = CustomerForm(formdata=request.form, obj=customer_info) if request.method == 'POST' and form.validate(): # delete the item from the database db.session.delete(customer_info) db.session.commit() flash('Cliente eliminado!') return redirect('/') return render_template('delete_customer.html', form=form) else: return 'Error deleting #{id}'.format(id=id)
def add(request): if request.method == 'POST': # if method was post (form submission), fill form with post data form = CustomerForm(request.POST) form_valid = form.is_valid() if form_valid: # if form is valid, save it and redirect back to mycustomers # commit=False tells form to not save the object to the database just yet and return it instead customer = form.save(commit=False) # set service_provider to the current customer before we save the object to the database customer.service_provider = request.user.service_provider customer.full_name = request.POST.get('name') + ' ' + request.POST.get('last_name') customer.last_reservation = None customer.save() return HttpResponseRedirect(reverse(mycustomers)) else: # on get request create empty form form = CustomerForm() # render form - new (get request) or invalid with error messages (post request) return render_to_response('customers/add.html', locals(), context_instance=RequestContext(request))
def customer_update(request): if request.method == 'POST': postdata = request.POST.copy() try: # c = Customer.objects.get(sn=request.POST['sn']) c = Customer.objects.get(sn=postdata.pop('sn')[0]) except Customer.DoesNotExist: raise Http404(module + ' not found') # else: # return HttpResponse('Invalid request.') form = CustomerForm(postdata, instance=c) if form.is_valid(): c_saved = form.save() serializer = JSONSimpleSerializer() return HttpResponse(serializer.serialize([c_saved,])) else: # if request.GET['id']: # c = Customer.objects.get(pk=int(request.GET['id'])) # form = CustomerForm(instance=c) # return render_to_response('modal/main_form.html',{'action':'Edit', 'module':module, 'form': form},context_instance=RequestContext(request)) # else: return HttpResponse('Invalid request.')
def customers(): if request.method == 'POST': form = CustomerForm(request.form) customer = Customer() if form.validate(): form.populate_obj(customer) db.session.add(customer) db.session.commit() return redirect(url_for('customers')) else: return render_template('new_customer.html', form=form) else: page = int(request.args.get('page', 1)) page_size = int(request.args.get('page_size', 10)) filter = request.args.get('filter', None) order_by = request.args.get('order_by', None) order = request.args.get('order', None) order = order if order in ['ASC', 'DESC'] else 'ASC' q = Customer.query if filter: q = q.filter(getattr(Customer, 'name').like('%{}%'.format(filter))) count = q.count() if order_by: q = q.order_by('{} {}'.format(order_by, order)) q = q.offset((page - 1) * page_size) customers = q.limit(page_size) total_pages = (count // page_size) + (0 if (count % page_size) == 0 else 1) return render_template('customers.html', customers=customers, page=page, page_size=page_size, count=count, total_pages=total_pages)
def customer_modify(request): form = CustomerForm(instance=request.user) if request.method == "POST": form = CustomerForm(request.POST, instance=request.user) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, _(u'信息修改成功')) return HttpResponseRedirect(reverse('home')) return render_to_response("core/customer_modify.html", { 'form': form, }, context_instance=RequestContext(request))
def edit(request, id): customer = get_object_or_404(Customer, id=id) if request.method == 'POST': form = CustomerForm(request.POST, instance=customer) form_valid = form.is_valid() if form_valid: customer = form.save() customer.full_name = request.POST.get( 'name') + ' ' + request.POST.get('last_name') customer.save() return HttpResponseRedirect(reverse(mycustomers)) else: form = CustomerForm(instance=customer) return render_to_response('customers/edit.html', locals(), context_instance=RequestContext(request))
def index(request): form = CustomerForm(request.POST) if (request.method == 'POST'): if (form.is_valid()): form.save() stu = Customer.objects.all() UserList = User.objects.all() for tm in stu: f = 0 for che in UserList: if (tm.name == che.username): f = 1 break if f == 0: user = User.objects.create_user(username=tm.name, password=tm.Password, email='*****@*****.**') #print form.cleaned_data[Customer.name] #user = User.objects.create_user(username = {{form.name}}, # password = {{form.RollNo}}, # email = '*****@*****.**' # ) message = 'Successfully Registered' #return render(request,'success.html',{'message': message}) return redirect("/success/", {'message': message}) else: form_error = "(Registration Failed. Username Exists!)" return render(request, 'index.html', { 'form': form, 'form_error': form_error }) else: form = CustomerForm(request.POST) return render(request, 'index.html', {'form': form})
def add(request): if request.method == 'POST': # if method was post (form submission), fill form with post data form = CustomerForm(request.POST) form_valid = form.is_valid() if form_valid: # if form is valid, save it and redirect back to mycustomers # commit=False tells form to not save the object to the database just yet and return it instead customer = form.save(commit=False) # set service_provider to the current customer before we save the object to the database customer.service_provider = request.user.service_provider customer.full_name = request.POST.get( 'name') + ' ' + request.POST.get('last_name') customer.last_reservation = None customer.save() return HttpResponseRedirect(reverse(mycustomers)) else: # on get request create empty form form = CustomerForm() # render form - new (get request) or invalid with error messages (post request) return render_to_response('customers/add.html', locals(), context_instance=RequestContext(request))
def index(request, template): user = request.user devices = Device.objects.all() assets = Assets.objects.all() pag_list = [] if user.get_profile().asset_edit: pag_list += assets if user.get_profile().parts_edit: pag_list += devices elif user.get_profile().parts_edit: pag_list += devices cus_form = CustomerForm() bom_form = BomForm() device_form = DeviceForm() asset_form = AssetsFrom() if request.method == "POST": if request.POST['subname'] == 'add_device': try: name = request.POST.getlist('bom_sns') if len(list(set(name))) == 1 and list(set(name))[0] == '': #全为空 pass else: new_device = Device() dev = {} for i in name: try: bom = Bom.objects.get(bom_sn=i) if bom.bom_name == u'ser' and dev.has_key(u'ser'): pass else: dev[bom.bom_name] = (bom, bom.bom_sn) except Exception,e: pass if dev.has_key('ser'): new_device.device_sn = dev['ser'][1] bom = Bom.objects.get(bom_sn=dev['ser'][1]) bom.bom_status = 'inuse' bom.save() new_device.save() for key in dev: if key != 'ser': new_device.device_boms.add(dev[key][0]) dev[key][0].bom_status = 'inuse' dev[key][0].save() new_device.save() return HttpResponseRedirect(reverse('index')) except: pass elif request.POST['subname'] == 'add_cus': cus_form = CustomerForm(request.POST) if cus_form.is_valid(): cus_form.save() return HttpResponseRedirect(reverse('index')) else: err_msg = 'error' elif request.POST['subname'] == 'add_asset': asset_form = AssetsFrom(request.POST) if asset_form.is_valid(): asset_form.save() return HttpResponseRedirect(reverse('index')) else: bom_form = BomForm(request.POST) if bom_form.is_valid(): bom_form.save() return HttpResponseRedirect(reverse('index')) else: err_msg = 'error' page = request.GET.get('page', '') paginator = Paginator(pag_list,'20') try: contacts = paginator.page(page) except PageNotAnInteger: contacts = paginator.page('1') except EmptyPage: contacts = paginator.page(paginator.num_pages) return TemplateResponse(request, template,{'cus_form':cus_form, 'bom_form':bom_form, 'devices':devices, 'asset_form':asset_form, 'contacts':contacts, 'pages':paginator})
def new_customer(): form = CustomerForm() return render_template('new_customer.html', form=form)
def edit_customer(id): customer = Customer.query.get(id) form = CustomerForm(obj=customer) return render_template('edit_customer.html', form=form, customer=customer)
def newmultiple(request): '''This view corresponds to adding a new customer''' # Creating title for the page title = 'New Customer' # Creating blank customer record for now. customerObj = Customer() # Creating new customer form customerForm = CustomerForm() # Creating new subscription formset. subscription_formset = inlineformset_factory(Customer, Subscription, fields=('feed','length'),form=SubscriptionForm,extra=1) # Returning form back with pre-populdated data context = { 'title': title, 'customerForm':customerForm, 'subscription_formset': subscription_formset, } # Bizare way of establishing now a relationship with the blank customer record. formset = subscription_formset(instance=customerObj) if request.POST: # Creating new customer form object that will be sent to template. customerForm = CustomerForm(request.POST) #Grabbing email address from form. email = customerForm['email'].value() # Saving customer form customerFormObj = customerForm.save(commit=False) # Populating formset with post data. formset = subscription_formset(request.POST, instance=customerFormObj) success_message = 'SUCCESS' # Checking to see if both forms are valid. if customerForm.is_valid() and formset.is_valid(): # Saving both customer form and subscription form. customerForm.save() formset.save() # Filling in rest of needed data in local database. dbObj = dbInteraction(email) dbObj.createCredentials() # Getting customer id this will be sent to the status view. customerID = dbObj.retrieveCustomerID() # Getting domain name based on the username that is currently in the database for the user. esDomainName = dbObj.retrieveUsername() # Creating Elasticsearch Domain, sending in domain name. This is what the elasticsearch cluster will be called. dbObj.createESDomain(str(esDomainName)) # Creating SQS queue for the data feed that was selected. dbObj.createQueueNames() # Created the needed resources in amazon. amznObj = amzn(email) # Creating queue in amazon amznObj.createQueues() # Creating credentials in amazon. amznObj.createCredentials() else: # Print errors associated with submitted error_message = 'ERROR PLEASE CORRECT FORM FIELD.' #Context creation this will hold a success message that indicates there was a problem with form submission. context = { 'title': title, 'customerForm':customerForm, 'subscription_formset': formset, 'success_message': error_message, } # Sending site to site form to sitetosite.html template. return render(request, 'feeds/newmultiple.html', context) # Creating first context this is a total success of all forms. context = { 'title': title, 'customerForm':customerForm, 'subscription_formset': formset, 'success_message': success_message, 'customer_id': customerID } # Sending site to site form to sitetosite.html template. return render(request, 'feeds/newmultiple.html', context) # Sending site to site form to sitetosite.html template. return render(request, 'feeds/newmultiple.html', context)
def post(self, obj_id=None): """ Post customer(s) Create a new customer/ Update a customer --- tags: - customers parameters: - in: path name: obj_id - in: body name: body schema: id: Customer required: - first_name - last_name optional: - address - phone_number properties: first_name: type: string description: first name for customer last_name: type: string description: last name for customer address: type: string description: address for customer phone_number: type: string description: phone number for customer responses: 201: description: Customer created """ data = self.prepare_data() if obj_id: form = UpdateForm(data, csrf_enabled=False) if form.validate(): customer = Customer.get_by_id(int(obj_id)) if not customer: abort(404, message="Customer with key ({}) not found".format(obj_id)) customer.first_name = form.first_name.data if form.first_name.data else customer.first_name customer.last_name = form.last_name.data if form.last_name.data else customer.last_name customer.phone_number = form.phone_number.data if form.phone_number.data else customer.phone_number customer.address = form.address.data if form.address.data else customer.address customer.put() output = self.output_fields output.update(self.resource_fields) return marshal(customer, output), 200 else: error_data = self.prepare_errors(form.errors) raise CustomException(code=400, name='Validation Failed', data=error_data) else: form = CustomerForm(data, csrf_enabled=False) if form.validate(): customer = Customer(first_name=form.first_name.data, last_name=form.last_name.data, phone_number=form.phone_number.data, address=form.address.data) customer.put() customer.id = str(customer.key.id()) customer.put() output = self.output_fields output.update(self.resource_fields) return marshal(customer, output), 201 error_data = self.prepare_errors(form.errors) raise CustomException(code=400, name='Validation Failed', data=error_data)