def createcustomer_self(request): if request.method=="POST": form=CustomerForm(request.POST) form.save() customer=Customer.objects.order_by('-customer_id')[0] request.session['sess_cust_id']=customer.customer_id return redirect('/')
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)
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)
def customers(): form = CustomerForm() shop_session = sfy.Session(session['shop_url'], '2019-04', session['token']) # activate the shopify session to use resources. sfy.ShopifyResource.activate_session(shop_session) if request.method == 'POST': if form.validate_on_submit(): generate_fake_customer_data(form.number_of_customers_field.data) # create_fake_products_and_variants(form.number_of_products_field.data, 5) return render_template('customers.html', form=form)
def get(self, request): edit = request.GET.get("edit") if edit: c = Customer.objects.get(id62=edit) c_form = CustomerForm(instance=c) u_form = UserForm(instance=User.objects.get(id=c.created_by_id)) else: c_form = CustomerForm() u_form = UserForm() return self.render_to_response({"form":{'user':u_form, 'customer':c_form}})
def create(): form = CustomerForm(request.form) msg = request.args.get('msg') if request.method == 'GET': customers = Customer.query.all() return render_template('layouts/default.html', content=render_template('pages/customers.html', form=form, msg=msg, customers=customers)) if form.validate_on_submit(): # assign form data to variables title = request.form.get('title', '', type=str) gcpCustomerId = request.form.get('gcpCustomerId', '', type=str) notes = request.form.get('notes', '', type=str) customerActive = True # filter customer out of database through title customer = Customer.query.filter_by(title=title).first() if customer: #do update customer.title = title customer.gcpCustomerId = gcpCustomerId customer.notes = notes # commit change and save the object db.session.commit() msg = 'Customer Updated' else: #do insert customer = Customer(title, gcpCustomerId, notes) customer.save() msg = 'Customer Created' customers = Customer.query.all() return render_template('layouts/default.html', content=render_template('pages/customers.html', form=form, msg=msg, customers=customers)) else: return render_template('layouts/default.html', content=render_template('pages/customers.html', form=form, msg="shit broke"))
def customer(): form = CustomerForm() if form.validate_on_submit(): first = form.first_name.data last = form.last_name.data return redirect( url_for('inventory', first=first.title(), last=last.title(), title='Cars')) return render_template('form.html', form=form, title='Customer Lookup')
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)
def get(self, request): data = {'id': 0, 'currency_code': 153} form = CustomerForm(initial=data) args = {'form': form, 'title': 'Customers', 'posts': data} return render(request, self.template_name, args)
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)
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)
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)
def save_reset_cus_1(id,search_d): form = CustomerForm() customer = Customer.query.filter_by(id = id).first() customer.genre = form.c_type.data customer.price_banci = form.price_banci.data db.session.add(customer) db.session.commit() return redirect(url_for('user.reset_cus',id = id,search_d=search_d))
def one_info(id): form = CustomerForm() form.project.choices = [('','')]+[(a.project,a.project) for a in AllProject.query.all()] customer = Customer.query.filter_by(id = id).first() form.project.data = customer.project form.c_type.data = customer.genre sale_cus_info = SaleCustomerInfo.query.filter_by(c_name_id=id) search_d={} return render_template('one_info.html',customer = customer,form = form,sale_cus_info = sale_cus_info,username = current_user.username,search_d = search_d)
def add_cus_form(): username = current_user.username sale = User.query.filter_by(username = username).first() flag = sale.flag.split(',') if '0' not in flag: return '权限不足' form = CustomerForm() # form.project.choices = [('','')]+[(a.project,a.project) for a in AllProject.query.all()] return render_template('add_cus_form.html',form = form,username = current_user.username)
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))
def customers(): form = CustomerForm() if form.validate_on_submit(): full_name = form.first_name.data.title( ) + ' ' + form.last_name.data.title() cars = db.session.execute(''' SELECT full_name, make, model, year, color FROM car INNER JOIN customer ON car.cust_id = customer.cust_id WHERE customer.full_name = '{}' '''.format(full_name)) return render_template('form.html', title='Customers', form=form, cars=cars) return render_template('form.html', title='Customers', form=form)
def reset_cus(id,search_d): form = SearchForm() form.c_project.choices = [('','')]+[(a.project,a.project) for a in AllProject.query.all()] form1 = CustomerForm() form1.project.choices = [('','')]+[(a.project,a.project) for a in AllProject.query.all()] customer = Customer.query.filter_by(id = id).first() form1.project.data = customer.project form1.c_type.data = customer.genre sale_cus_info = SaleCustomerInfo.query.order_by(SaleCustomerInfo.id.desc()).filter_by(c_name_id = id) search_d = eval(search_d) search_cus = Customer.query.filter_by(**search_d) return render_template('reset_cus.html',customer = customer,form = form,sale_cus_info = sale_cus_info,username = current_user.username,form1=form1,search_cus = search_cus,search_d = search_d)
def customer_add_edit(record_id='0'): if record_id == '0': record = Customer(user=current_user) else: record = Customer.query.by_user(current_user).filter( Customer.id == record_id).first() form = CustomerForm(obj=record) try: form.populate_obj(record) except: pass if form.validate_on_submit(): # it's submit! db.session.add(record) db.session.commit() if record_id == '0': return redirect('/customers') else: return redirect('/customer/' + record_id) print_errors(form) return render_template('forms/customer_modal.html', form=form, record=record)
def createcustomer(request): if request.method=="POST": form=CustomerForm(request.POST) form.save() return redirect('/customer') form=CustomerForm() return render(request,'createcustomer.html',{'form':form})
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) )
def editCustomer(customerId): form = CustomerForm(request.form) msg = None customer = Customer.query.filter_by(id=customerId).first() customers = Customer.query.all() if request.method == 'GET': return render_template('layouts/default.html', content=render_template('pages/customers.html', form=form, msg=msg, customers=customers, customer=customer)) if form.validate_on_submit(): # assign form data to variables title = request.form.get('title', '', type=str) gcpCustomerId = request.form.get('gcpCustomerId', '', type=str) notes = request.form.get('notes', '', type=str) c_id = request.form.get('id', '', type=int) customerActive = True # filter customer out of database through id customer_update = Customer.query.filter_by(id=c_id).first() if customer_update: #do update customer_update.title = title customer_update.gcpCustomerId = gcpCustomerId customer_update.notes = notes # commit change and save the object db.session.commit() msg = 'Customer Updated' else: msg = 'Something Broke' return redirect(url_for('create', msg=msg))
def save_reset_cus(id): form = CustomerForm() customer = Customer.query.filter_by(id = id).first() c_type = form.c_type.data price_banci = form.price_banci.data customer.c_name = form.name.data if customer.genre!=c_type or customer.price_banci!=price_banci: old = Old_Active(cus_id=customer.id,old_genre=customer.genre,old_banci=customer.price_banci) customer.genre = c_type customer.price_banci = price_banci db.session.add(old) db.session.commit() return redirect(url_for('user.open',id = id))
def customer(): form = CustomerForm() first_name = form.first_name.data, last_name = form.last_name.data # customer = Customer.query.all() customer = Customer.query.all() return render_template('customer.html', form=form, title='Customer', customer=customer, first_name=first_name)
def customer_update_view(request, customer_id): c = retrieve_customer(customer_id) form = CustomerForm( initial={ 'given_name': c.given_name, 'company_name': c.company_name, 'email_address': c.email_address, 'phone_number': c.phone_number, 'discount': c.note }) if request.method == 'GET': return render(request, "customer_form.html", {'form': form}) else: update_customer(customer_id, request) return redirect('customer_list_view')
def add_cus(): form = CustomerForm() username = current_user.username customer = Customer() customer.c_name = form.name.data customer.phone = form.phone.data if len(customer.phone)!=11: flash('手机号不足11位') return redirect(url_for('user.add_cus_form')) if len(request.form.getlist('project'))==0: flash('项目不能为空') return redirect(url_for('user.add_cus_form')) if request.form.get('genre')==None: flash('类型不能为空') return redirect(url_for('user.add_cus_form')) if form.price_banci.data=='': flash('价格班次不能为空') return redirect(url_for('user.add_cus_form')) search_p = { 'phone':form.phone.data, 'date_time':str(datetime.date.today()) } if Customer.query.filter_by(**search_p).count(): flash('客户今日已入库') return redirect(url_for('user.add_cus_form')) project_l = request.form.getlist('project') project = ','.join(project_l) customer.project = project customer.genre = request.form.get('genre') customer.sale_name = current_user.username customer.date_time = str(datetime.date.today()) customer.price_banci = form.price_banci.data customer.readed = False db.session.add(customer) db.session.commit() search_all = {'c_name':form.name.data, 'phone':form.phone.data, 'project':project, 'genre':request.form.get('genre'), 'sale_name':current_user.username, 'date_time':str(datetime.date.today()) } search_d = dict((key,value)for key,value in search_all.items() if value!='') cus = Customer.query.filter_by(**search_d).first() return redirect(url_for('user.one_info',id = cus.id))
def post(self, request): myid = self.request.POST.get('postpk') mvtype = self.request.POST.get('postdir') form = self.request.POST.get('form') #oCustomer1 = get_object_or_404(Customer, id=myid) oCustomer1 = Customer.objects.filter(id=myid).order_by('id')[0:1] if not oCustomer1.exists(): if mvtype == 'prev': myid = Customer.objects.latest('id').id oCustomer_move = Customer.objects.filter( id=myid).order_by('id')[0:1] elif mvtype == 'next': myid = 0 oCustomer_move = Customer.objects.filter( id__gt=myid).order_by('id')[0:1] elif mvtype == 'equals': myid = 0 oCustomer_move = oCustomer1 elif mvtype == 'next': oCustomer_move = Customer.objects.filter( id__gt=oCustomer1[0].id).order_by('id')[0:1] elif mvtype == 'prev': oCustomer_move = Customer.objects.filter( id__lt=oCustomer1[0].id).order_by('-id')[0:1] elif mvtype == 'equals': oCustomer_move = oCustomer1 if oCustomer_move.exists(): #data = {'id': oCustomer_move[0].id, 'Code': oCustomer_move[0].Code, 'Name': oCustomer_move[0].Name, 'Address': oCustomer_move[0].Address, 'PostCode': oCustomer_move[0].PostCode} data = {'id': oCustomer_move[0].id} else: data = {'id': 0} form = CustomerForm(form, instance=oCustomer_move[0]) #oCustomerMoveTo = get_object_or_404(Customer, id=myid) args = {'form': form, 'title': 'Customer', 'oPost': data} #args={'title':'Customer','oPost': oCustomerMoveTo} return render(request, self.template_name, args)
def open(id): customer = Customer.query.filter_by(id = id).first() if customer.sale_name==current_user.username: form = SearchForm() form.c_project.choices = [('','')]+[(a.project,a.project) for a in AllProject.query.all()] form1 = CustomerForm() form1.project.choices = [('','')]+[(a.project,a.project) for a in AllProject.query.all()] form1.project.data = customer.project form1.c_type.data = customer.genre sale_cus_info = SaleCustomerInfo.query.order_by(SaleCustomerInfo.id.desc()).filter_by(c_name_id = id) comments = Comment.query.filter_by(c_name_id = id) old_act = Old_Active.query.order_by(Old_Active.id.desc()).filter(Old_Active.cus_id==id) for comment in comments: if ReadComment.query.filter_by(cus_id = id,user = current_user.username,comment_id=comment.id).first()==None: read = ReadComment() read.cus_id = id read.user = current_user.username read.comment_id = comment.id db.session.add(read) db.session.commit() return render_template('sale_open.html',customer = customer,form = form,sale_cus_info = sale_cus_info,username = current_user.username,form1=form1,comments = comments,old_act=old_act) else: return '这不是您的客户呦'
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}})
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)
def updatecustomer(request,id): customer=Customer.objects.get(customer_id=id) form=CustomerForm(request.POST,request.FILES,instance=customer) form.save() return redirect('/customer')
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)