def test_01_addOffer(self): offer = Offer(**self.offer_dict_1) second_offer = Offer(**self.offer_dict_2) third_offer = Offer(**self.offer_dict_3) self.assertTrue(DB.addOffer(offer)) self.assertTrue(DB.addOffer(second_offer)) self.assertTrue(DB.addOffer(third_offer))
def test_returns_false_if_offer_is_coming_from_provider(self, app): # given offer = Offer() offer.lastProviderId = 21 # then assert offer.isEditable == False
def test_offer_is_digital_if_it_has_an_url(): # given offer = Offer() offer.url = 'http://url.com' # when / then assert offer.isDigital
def shops_updater(bot: Bot, job: Job) -> None: logger.debug("Entering: shops_updater") resp = requests.get(config.SHOP_API, verify=False) if resp.status_code == 200: logger.debug('Retrieved shop data. Dropping and recreating tables.') dbOffer.drop_table(with_all_data=True) dbShop.drop_table(with_all_data=True) db.create_tables(True) shops = resp.json() with orm.db_session: # TODO: Get f*****g marshmallow deserialisation working for shop in shops: logger.debug("creating shop %s", shop['name']) s = dbShop(link=shop['link'], name=shop['name'], ownerName=shop['ownerName'], ownerCastle=shop['ownerCastle'], kind=shop['kind'], mana=shop['mana']) for offer in shop['offers']: logger.debug("adding offer %s to shop %s", offer['item'], shop['name']) s.offers.create(**offer) else: logger.debug("Exiting: shops_updater") return
def test_booking_completed_url_gets_normalized(): # Given product = Product() product.url = 'javascript:alert("plop")' offer = Offer() offer.id = 1 offer.product = product stock = Stock() user = User() user.email = '*****@*****.**' booking = Booking() booking.token = 'ABCDEF' booking.stock = stock booking.stock.offer = offer booking.user = user # When completedUrl = booking.completedUrl # Then assert completedUrl == 'http://javascript:alert("plop")'
def create_offer(payload): body = request.get_json() if not body: abort(400, 'Request body is missing.') if body.get('title') is None: abort(400, '"title" is required in the request body.') # Create a new record o = Offer( title=body.get('title'), contents=body.get('contents', ''), event_time=body.get('event_time'), # Null if not found finalized=body.get('finalized', False), topics=[get_topic(name=t) for t in body.get('topics', [])], panelists=[ get_panelist(name=p) for p in body.get('panelists', []) ] ) try: o.insert() offer_id = o.id except Exception: abort(422, 'Database error: Insertion failed.') return jsonify({ 'success': True, 'message': 'Offer record has been created successfully.', 'id': offer_id }), 201
def test_returns_none_if_no_mediations_exist_on_offer(self): # given offer = Offer() offer.mediations = [] # then assert offer.activeMediation is None
def fetch_and_process_offer(offer_id): offer = Scraper.scrap_offer_details_page(offer_id) if not offer: return if not offer.get('location'): location = geocode_city_country(offer['city'].lower(), offer['country'].lower()) # Lower for better cache offer['location'] = location or None Offer.upsert(session, offer)
def test_date_range_is_empty_if_event_has_no_stocks(): # given offer = Offer() offer.product = create_product_with_event_type() offer.stocks = [] # then assert offer.dateRange == DateTimes()
def test_date_range_is_empty_if_offer_is_on_a_thing(): # given offer = Offer() offer.product = create_product_with_thing_type() offer.stocks = [] # then assert offer.dateRange == DateTimes()
def test_returns_false_if_all_stocks_have_no_booking_limit_datetime(self): # given offer = Offer() stock1 = create_stock(booking_limit_datetime=None) stock2 = create_stock(booking_limit_datetime=None) stock3 = create_stock(booking_limit_datetime=None) offer.stocks = [stock1, stock2, stock3] # then assert offer.isFinished is False
def test_returns_none_if_all_mediations_are_deactivated(self): # given offer = Offer() offer.mediations = [ create_mediation(offer, is_active=False), create_mediation(offer, is_active=False) ] # then assert offer.activeMediation is None
def test_returns_true_if_all_stocks_have_past_booking_limit_datetime(self): # given now = datetime.utcnow() offer = Offer() stock1 = create_stock(booking_limit_datetime=now - timedelta(weeks=3)) stock2 = create_stock(booking_limit_datetime=now - timedelta(weeks=2)) stock3 = create_stock(booking_limit_datetime=now - timedelta(weeks=1)) offer.stocks = [stock1, stock2, stock3] # then assert offer.isFinished is True
def test_date_range_matches_the_occurrence_if_only_one_occurrence(): # given offer = Offer() offer.product = create_product_with_event_type() offer.stocks = [ create_stock(offer=offer, beginning_datetime=two_days_ago, end_datetime=five_days_from_now) ] # then assert offer.dateRange == DateTimes(two_days_ago, five_days_from_now)
def test_returns_false_if_any_stock_has_future_booking_limit_datetime( self): # given now = datetime.utcnow() offer = Offer() stock1 = create_stock(booking_limit_datetime=now - timedelta(weeks=3)) stock2 = create_stock(booking_limit_datetime=None) stock3 = create_stock(booking_limit_datetime=now + timedelta(weeks=1)) offer.stocks = [stock1, stock2, stock3] # then assert offer.isFinished is False
def test_returns_false_if_stocks_have_none_available_quantity(self): # given offer = Offer() user = create_user() stock1 = create_stock(available=None) stock2 = create_stock(available=None) create_booking(user, stock=stock1, quantity=1) create_booking(user, stock=stock2, quantity=1) offer.stocks = [stock1, stock2] # then assert offer.isFullyBooked is False
def fill_offer_with_new_data(product_dict: str, user: User) -> Offer: product = Product() url = product_dict.get('url') if url: is_url_safe(url) product_dict['isNational'] = True product.populate_from_dict(product_dict) check_user_can_create_activation_event(user, product) offer = Offer() offer.populate_from_dict(product_dict) offer.product = product return offer
def test_raises_error_when_offer_is_not_editable(self): # given offer = Offer() offer.lastProviderId = "42" # when with pytest.raises(ApiErrors) as error: check_offer_is_editable(offer) # then assert error.value.errors['global'] == [ "Les offres importées ne sont pas modifiables" ]
def test_stocks_with_past_booking_limit_datetimes_are_ignored(self): # given offer = Offer() user = create_user() stock1 = create_stock(available=2, booking_limit_datetime=datetime.utcnow() - timedelta(weeks=3)) stock2 = create_stock(available=1) stock3 = create_stock(available=1) create_booking(user, stock=stock2, quantity=1) create_booking(user, stock=stock3, quantity=1) offer.stocks = [stock1, stock2, stock3] # then assert offer.isFullyBooked is True
def test_on_datetime_list_returns_string_with_date_in_ISO_8601_list(self): # Given offer = Offer() offer.stocks = [ create_stock(offer=offer, beginning_datetime=now, end_datetime=now + timedelta(hours=3)) ] # When serialized_list = serialize(offer.dateRange) # Then for datetime in serialized_list: self._assert_is_in_ISO_8601_format(datetime)
def test_offer_as_dict_returns_dateRange_in_ISO_8601(self): # Given offer = Offer() offer.stocks = [ create_stock(offer=offer, beginning_datetime=datetime(2018, 10, 22, 10, 10, 10), end_datetime=datetime(2018, 10, 22, 13, 10, 10)) ] # When offer_dict = as_dict(offer, includes=["dateRange"]) # Then assert offer_dict['dateRange'] == [ '2018-10-22T10:10:10Z', '2018-10-22T13:10:10Z' ]
def addOffers(self, offers, site): if not offers: return newOffers = [] for offer in offers: try: image_offer = urlfetch.Fetch(url=offer[1], deadline=10).content except urlfetch.Error: image_offer = urlfetch.fetch(url="http://www.escolhaofertas.com.br/static/images/img_404.png").content logging.error("Image Timeout") newOffers.append( Offer( link=offer[0], img=offer[1], image=db.Blob(image_offer), desc=offer[2] + offer[3], price="", site_name=site, views=0, ) ) db.put(newOffers) memcache.flush_all() memcache.set("num_offers", Offer.all().count()) logging.info("Offers length :" + str(len(newOffers))) self.response.out.write(site + ": Offers added")
def retrieve_new_offers() -> None: """Extract and store offers from the Offers MS for each product. First creates OffersBatch record to which all created offers are tied. Ignores offers not matching the schema or empty responses :return: """ oms = OffersMsClient() ob = OffersBatch() db.session.add(ob) for p in Product.query.all(): for offer_data_raw in oms.extract_offers(p): try: offer_data = offers_schema_external.load(offer_data_raw) offer_data['id_external'] = offer_data.pop('id') except (ValidationError, KeyError) as e: current_app.logger.warning( f'offer validation failed with {getattr(e, "messages", str(e))} {offer_data_raw=}' ) continue o = Offer(product_id=p.id, offers_batch_id=ob.id, **offer_data) db.session.add(o) db.session.commit()
def test_create_payment_for_booking_when_no_iban_on_venue_should_take_payment_info_from_offerer( app): # given user = create_user() stock = create_stock(price=10, available=5) offerer = create_offerer(name='Test Offerer') venue = create_venue(offerer, name='Test Venue') offerer_bank_information = create_bank_information(bic='QsdFGH8Z555', iban='cf13QSDFGH456789', offerer=offerer) venue_bank_information = create_bank_information(bic=None, iban=None, venue=venue) booking = create_booking(user, stock=stock, quantity=1) booking.stock.offer = Offer() booking.stock.offer.venue = venue booking.stock.offer.venue.managingOfferer = offerer booking_reimbursement = BookingReimbursement( booking, ReimbursementRules.PHYSICAL_OFFERS, Decimal(10)) # when payment = create_payment_for_booking(booking_reimbursement) # then assert payment.iban == 'CF13QSDFGH456789' assert payment.bic == 'QSDFGH8Z555'
def test_create_payment_for_booking_when_iban_is_on_venue_should_take_payment_info_from_venue( app): # given user = create_user() stock = create_stock(price=10, available=5) offerer = create_offerer(name='Test Offerer') venue = create_venue( offerer, name='Test Venue', ) booking = create_booking(user, stock=stock, quantity=1) offerer_bank_information = create_bank_information(bic='Lajr93', iban='B135TGGEG532TG', offerer=offerer) venue_bank_information = create_bank_information(bic='LokiJU76', iban='KD98765RFGHZ788', venue=venue) booking.stock.offer = Offer() booking.stock.offer.venue = venue booking.stock.offer.venue.managingOfferer = offerer booking_reimbursement = BookingReimbursement( booking, ReimbursementRules.PHYSICAL_OFFERS, Decimal(10)) # when payment = create_payment_for_booking(booking_reimbursement) # then assert payment.iban == 'KD98765RFGHZ788' assert payment.bic == 'LOKIJU76'
def add_offer(request): enterprise = Enterprise.objects.get(pk=request.user.id) error = None # If the enterprise has closed offers without feedback if enterprise.get_closed_offers_without_feedback(): request.flash[ 'error_message'] = 'No puede crear nuevas ofertas hasta entregar el feedback de las ya cerradas' return HttpResponseRedirect( reverse('bolsa_trabajo.views_enterprise.offer')) if request.method == 'POST': form = OfferForm(request.POST) if form.is_valid(): offer = Offer.create_from_form(enterprise, form) offer.save() UserProfile.notify_staff_of_new_offer() request.flash[ 'message'] = 'Oferta propuesta exitosamente, por favor espere a que un encargado la valide' url = reverse('bolsa_trabajo.views_account.index') return HttpResponseRedirect(url) else: form = OfferForm() return append_user_to_response(request, 'enterprise/add_offer.html', { 'offer_form': form, 'error': error })
def add_offer(request): enterprise = Enterprise.objects.get(pk=request.user.id) error = None # If the enterprise has closed offers without feedback if enterprise.get_closed_offers_without_feedback(): request.flash['error_message'] = 'No puede crear nuevas ofertas hasta entregar el feedback de las ya cerradas' return HttpResponseRedirect(reverse('bolsa_trabajo.views_enterprise.offer')) if request.method == 'POST': form = OfferForm(request.POST) if form.is_valid(): offer = Offer.create_from_form(enterprise, form) offer.save() UserProfile.notify_staff_of_new_offer() request.flash['message'] = 'Oferta propuesta exitosamente, por favor espere a que un encargado la valide' url = reverse('bolsa_trabajo.views_account.index') return HttpResponseRedirect(url) else: form = OfferForm() return append_user_to_response(request, 'enterprise/add_offer.html', { 'offer_form': form, 'error': error })
def test_create_payment_for_booking_with_common_information(app): # given user = create_user() stock = create_stock(price=10, available=5) booking = create_booking(user, stock=stock, quantity=1) booking.stock.offer = Offer() booking.stock.offer.venue = Venue() offerer = create_offerer() offerer_bank_information = create_bank_information(bic='QSDFGH8Z555', iban='CF13QSDFGH456789', offerer=offerer) booking.stock.offer.venue.managingOfferer = offerer booking_reimbursement = BookingReimbursement( booking, ReimbursementRules.PHYSICAL_OFFERS, Decimal(10)) # when payment = create_payment_for_booking(booking_reimbursement) # then assert payment.booking == booking assert payment.amount == Decimal(10) assert payment.reimbursementRule == ReimbursementRules.PHYSICAL_OFFERS.value.description assert payment.reimbursementRate == ReimbursementRules.PHYSICAL_OFFERS.value.rate assert payment.comment is None assert payment.author == 'batch' assert payment.transactionLabel == 'pass Culture Pro - remboursement 2nde quinzaine 10-2018'
def test_does_not_raise_error_when_offer_type_is_editable(self): # given offer = Offer() # when try: check_offer_is_editable(offer) except: assert False
def get(self): numOffers = memcache.get('num_offers') t = datetime.today() uploaded_date_offers = t.strftime("%d/%m/%y") offers = Offer.all().order("__key__").fetch(PAGESIZE) offers = list(offers) #uploaded_date_offers = memcache.get('last_update') self.render('index.html', offers=offers, num_offers=numOffers, uploaded_date_offers=uploaded_date_offers)
def offer(): error = False try: player = Player() Player.insert(player) offer = Offer(player_one = player.id) Offer.insert(offer) session['userId'] = player.id except: error = True db.session.rollback() print(sys.exc_info()) finally: db.session.close() if error: return 'error' else: return redirect(url_for('chess'))
def createOffer(): if request.method == "POST": data = request.get_json(force=True) createdTime = ( datetime.datetime.now() + datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S") updateTime = ( datetime.datetime.now() + datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S") email_time = "2016-12-19 " + data["email_time"] + ":00" emailTime = float( time.mktime(time.strptime(email_time, '%Y-%m-%d %H:%M:%S'))) offer = Offer( int(data["user_id"]), int(data["customer_id"]), data["status"], data["contract_type"], data["contract_num"], float(data["contract_scale"]), data["os"], data["package_name"], data["app_name"], data["app_type"].encode('utf-8'), data["preview_link"], data["track_link"], data["material"], data["startTime"], data["endTime"], str(data["platform"]), str(data["country"]), float(data["price"]), float(data["daily_budget"]), data["daily_type"], float(data["total_budget"]), data["total_type"], data["distribution"], data["authorized"], data["named_rule"], data["KPI"].encode('utf-8'), data["settlement"].encode('utf-8'), data["period"].encode('utf-8'), data["remark"].encode('utf-8'), emailTime, str(data["email_users"]), int(data["email_tempalte"]), createdTime, updateTime) try: db.session.add(offer) db.session.commit() db.create_all() for i in data['country_detail']: history = History(offer.id, int(data["user_id"]), "default", createdTime, status=data["status"], country=i["country"], country_price=i["price"], price=data["price"], daily_budget=float(data["daily_budget"]), daily_type=data["daily_type"], total_budget=float(data["total_budget"]), total_type=data["total_type"], KPI=data["KPI"], contract_type=data["contract_type"], contract_scale=float(data["contract_scale"])) db.session.add(history) db.session.commit() db.create_all() return json.dumps({"code": 200, "message": "success"}) except Exception as e: print e return json.dumps({"code": 500, "message": "fail"})
def get(self, page_id): offer = memcache.get("page"+page_id) if not offer: offer = Offer.get_by_id(int(page_id)) memcache.set("page"+page_id,offer) if offer: self.render('index.html',offers=[offer],num_offers=-1, uploaded_date_offers=None) else: self.redirect('/static/pages/404.html')
def add_offer(): form = OfferForm() if form.validate_on_submit(): offer = Offer.query.filter_by(name=form.name.data).first() if not offer: db_session.add( Offer(form.name.data, form.cost.data, form.description.data, form.capacity.data)) db_session.commit() return redirect('/all_abonements') return render_template('add_offer.html', form=form)
def add_offer(): date = request.json['date'] username = request.json['username'] book_id = request.json['book_id'] new_offer = Offer(date, username, book_id) db.session.add(new_offer) db.session.commit() return jsonify(new_offer)
def post(self, call): ids = Offer.allocate_ids(size=1) user = self.user call = Key(urlsafe=call).get() taglio = self.request.get('taglio') offerta = self.request.get('offerta') o = Offer(id=ids[0]) o.team = user.key o.cut = taglio o.price = int(offerta) o.put() call.offers.append(o.key) call.put() self.render_template('message.html', params=dict(message="offerta ricevuta"))
def new(): c1=Category(cat="Football") c1.save() c2=Category(cat="Basketball") c2.save() c3=Category(cat="Hockey") c3.save() c4=Category(cat="Soccer") c4.save() c5=Category(cat="Random") c5.save() m1=Match(match="Washington v Dallas",cat=c1) m1.save() m2=Match(match="Wisconsin v Michigan",cat=c1) m2.save() m3=Match(match="Spartak v Celtic",cat=c4) m3.save() m4=Match(match="Arsenal v Chelsea",cat=c4) m4.save() m5=Match(match="Caps v Flyers",cat=c3) m5.save() o1=Offer(offer="Dallas",match=m1,odds=2.3) o1.save() o2=Offer(offer="Washington",match=m1,odds=5) o2.save() o3=Offer(offer="Soccer Riot",match=m3,odds=5) o3.save() u1 = User.objects.create_user('matt', '*****@*****.**', 'p') u1.save() u2=User.objects.create_user('mike', '*****@*****.**', 'p') u2.save() u3=User.objects.create_user('dan', '*****@*****.**', 'p') u3.save() u4=User.objects.create_user('scott', '*****@*****.**', 'p') u4.save() u5=User.objects.create_user('nick', '*****@*****.**', 'p') u5.save()
def get(self, page): offers_page = memcache.get("offers_page"+page) if offers_page is not None: logging.info("offers_page"+str(page)+" HIT") self.response.out.write(json.dumps(offers_page)) return offers = Offer.all().order("__key__").fetch(PAGESIZE + 1, (int(page)-1) * PAGESIZE) num_offers = len(offers) offers = offers[:PAGESIZE] if num_offers == PAGESIZE+1: response = self.createJsonOffers(page,offers) elif num_offers > 0: response = self.createJsonOffers(page,offers,0) else: response = '{more:-1}' memcache.set("offers_page"+page,response) logging.info("offers_page"+str(page)+" Miss") self.response.out.write(json.dumps(response))
def post(self, request, *args, **kwargs): invoice_id = kwargs['pk'] invoice = Invoice.objects.get( pk=invoice_id ) parameters = OfferParameters.objects.get( buyer=invoice.buyer, supplier=invoice.supplier) user = self.request.user context = {} context['invoice'] = invoice context['parameters'] = parameters company = user.person.company if invoice.buyer == company: context['buyer'] = True elif invoice.supplier == company: context['supplier'] = True else: context['invalid'] = True return HttpResponseRedirect('/dashboard/') ## change later # POST data option = request.POST.get('option') percent = request.POST.get('percent') days_acc = request.POST.get('days-acc') if utils.valid_offer(invoice, parameters, option, percent, days_acc): messages.info(request, "Good offer") # fix this later if option == '1': percent_param = parameters.alt_1_percent days_acc_param = parameters.alt_1_days elif option == '2': percent_param = parameters.alt_2_percent days_acc_param = parameters.alt_2_days elif option == '3': percent_param = parameters.alt_3_percent days_acc_param = parameters.alt_3_days discount_amount = utils.calculate_discount(invoice.amount, percent_param) # create new offer model object offer = Offer() offer.invoice = invoice offer.parameters = parameters offer.discount = percent_param offer.days_accelerated = days_acc_param offer.date_due = utils.calculate_date(invoice.due_date, days_acc_param) offer.amount = discount_amount offer.status = 'CLEARED' offer.profit = utils.calculate_profit(invoice.amount, discount_amount) offer.apr = utils.calculate_apr(percent_param, days_acc_param) offer.save() invoice.current_bid = offer invoice.status = 'CLEARED' invoice.save() ## fix this # utils.email_offer_confirmation(offer) ### need to send messages to respective parties ### perhaps have in Offer field ### the Person who did the offer else: messages.error(request, "Bad offer") return self.render(**context)
def create_dummy_objects(): s = LandingSite() s.page1_template = 'acai1.html' s.page1_name = 'acai version 1' s.page1_desc = "Ben's site" s.category = 'diet' s.total_offers = 2 s.active = True s.redirect_on_exit = True s.save() o = Offer() o.network_name = 'eadv' o.offer_name = 'Lean Spa US' o.offer_url = 'http://www.leanspa.com?s=' o.display_name = 'Lean Spa' o.offer_id = 10107 o.active = True o.payout = 50.00 o.save() o2 = Offer() o2.network_name = 'eadv' o2.offer_name = 'ColoThin' o2.offer_url = 'http://www.colothin.com?s=' o2.display_name = 'ColoThin' o2.offer_id = 2345 o2.active = True o2.price_old = '3.99' o2.price_new = '1.99' o2.coupon = 'COLOSAVE' o2.payout = 50.00 o2.save() os = OfferSet() os.offer1_id = 1 os.offer2_id = 2 os.total_offers = 2 os.category = 'diet' os.active = True os.save() sof = SiteOfferSet() sof.site = s sof.offer_set = os sof.save()
def Offer(establishment_id=None): form=AddOfferForm() from models import Establishment if(establishment_id==None): all_my_establishments = Establishment.query.filter_by(user_id=current_user.id).all() if(not all_my_establishments): flash('Please add establishment detail before its offers') return redirect(url_for('service_provider.Establishment')) form.establsihment.choices = [(establishment.id,establishment.establishment_name) for establishment in all_my_establishments] else: my_establishment = Establishment.query.filter_by(id=establishment_id).first() if (not my_establishment): flash('Please add establishment detail before its offers') return redirect(url_for('service_provider.Establishment')) form.establsihment.choices = [(establishment_id,my_establishment.establishment_name)] if form.validate_on_submit(): from models import Offer, sqlalchemy_obj from werkzeug import secure_filename import os from manage import my_app_obj print "Your establishment code is " + str(form.establsihment.data) new_offer_obj = Offer(offer_description=form.offer_description.data, validity=form.validity.data, establishments_id=form.establsihment.data, conditions=form.conditions.data, user_id=current_user.id) sqlalchemy_obj.session.add(new_offer_obj) sqlalchemy_obj.session.commit() file_path_string_comma_seperated = "" #http://stackoverflow.com/questions/23706370/wtforms-multi-selection-file-upload picture_count = 0 for a_picture in request.files.getlist("offer_picture"): #uploaded_files = request.files.getlist("offer_picture[]") ###############################################Uploading pictures print "Uploading " + a_picture.filename file_name = secure_filename(a_picture.filename) picture_storage_path = os.path.join(os.getcwd(),'static','gallery' , str(form.establsihment.data), str(new_offer_obj.id)) file_storage_path = "/".join(['gallery' , str(form.establsihment.data), str(new_offer_obj.id)]) print "Path of file storage is " + file_storage_path if not os.path.exists(picture_storage_path): os.makedirs(picture_storage_path) file_path_with_name = os.path.join(os.getcwd(),'static','gallery' , str(form.establsihment.data), str(new_offer_obj.id), file_name) if (picture_count==0): file_path_string_comma_seperated = str(file_storage_path+"/" + file_name) picture_count = picture_count + 1 else: file_path_string_comma_seperated = file_path_string_comma_seperated + "," + str(file_storage_path+"/" + file_name) print "Complete path is " + file_path_with_name a_picture.save(file_path_with_name) image_size(file_path_with_name) ###############################################Uploading pictures#################### new_offer_obj.offer_pictures_location = file_path_string_comma_seperated sqlalchemy_obj.session.commit() flash("Your offer is added, congratulations - Let's see customers now") return redirect(url_for('service_provider.index')) return render_template('service_provider/edit_offer.html', form=form)
def get(self,image_id): offer = Offer.get_by_id(int(image_id)) self.response.headers['Content-Type'] = 'image/jpeg' self.response.out.write(offer.image)
def get_instance_form(self, form, offer_slug, company): if Offer.objects.filter(slug=offer_slug).exists(): offer = Offer.objects.get(slug=offer_slug) else: offer = Offer() offer.job_title = form.cleaned_data['job_title'] offer.location = form.cleaned_data['location'] offer.type_contract = form.cleaned_data['type_contract'] offer.salary = form.cleaned_data['salary'] offer.state = 0 offer.offer_valid_time = datetime.now() + timedelta(days=30) skills = form.cleaned_data['skills'] offer.job_description = form.cleaned_data['job_description'] offer.company = company offer.save() for skill in skills: offer.skills.add(skill) return offer