def get_object(self): try: order = Order.objects.get(user=self.request.user, ordered=False) return order except ObjectDoesNotExist: raise Http404("You do not have an active order")
def _indexing(slug, reset=False): sources_index = {} sources = list(Source.objects.using('records').all()) for source in sources: sources_index[source.id] = source try: solr_address = settings.SOLR['host'] db_conf = settings.DATABASES.get( settings.SOLR['catalogs'][slug]['database'], None) except KeyError: raise Http404(u'Catalog not founded') if not db_conf: raise Exception( u'Settings not have inforamation about database, where contains records.' ) if db_conf['ENGINE'] != 'django.db.backends.mysql': raise Exception( u' Support only Mysql Database where contains records.') try: conn = MySQLdb.connect(host=db_conf['HOST'], user=db_conf['USER'], passwd=db_conf['PASSWORD'], db=db_conf['NAME'], port=int(db_conf['PORT']), compress=True, charset='utf8', use_unicode=True, cursorclass=MySQLdb.cursors.SSDictCursor) except MySQLdb.OperationalError as e: conn = MySQLdb.connect(unix_socket=db_conf['HOST'], user=db_conf['USER'], passwd=db_conf['PASSWORD'], db=db_conf['NAME'], port=int(db_conf['PORT']), compress=True, charset='utf8', use_unicode=True, cursorclass=MySQLdb.cursors.SSDictCursor) holdings_index = _load_holdings(conn) orgs_index = _load_orgs() sources_index = _load_sources() try: index_status = IndexStatus.objects.get(catalog=slug) except IndexStatus.DoesNotExist: index_status = IndexStatus(catalog=slug) # select_query = "SELECT * FROM records where deleted = 0 AND LENGTH(content) > 0 and record_id='ru\\\\nlrt\\\\1359411'" select_query = "SELECT * FROM records where deleted = 0 AND LENGTH(content) > 0" # if not getattr(index_status, 'last_index_date', None): # select_query = "SELECT * FROM records where deleted = 0 and content != NULL" # else: # select_query = "SELECT * FROM records where update_date >= '%s' and deleted = 0" % ( # str(index_status.last_index_date)) solr = sunburnt.SolrInterface( solr_address, http_connection=httplib2.Http(disable_ssl_certificate_validation=True)) docs = list() start_index_date = datetime.datetime.now() conn.query(select_query) rows = conn.use_result() res = rows.fetch_row(how=1) i = 0 while res: if not res[0]['content']: res = rows.fetch_row(how=1) continue zf = zipfile.ZipFile(io.BytesIO((res[0]['content']))) content = zf.read('1.xml').decode('utf-8') doc_tree = etree.XML(content) doc_tree = xslt_indexing_transformer(doc_tree) doc = doc_tree_to_dict(doc_tree) doc = add_sort_fields(doc) # для сортировки по тому, извлекаем строку содержащую номер тома или промежуток и посещаем резултат вычисления # в поле tom_f, которое в последствии сортируется # если трока типа т.1 то в том добавляется float 1 # если строка содержит т.1-2 то добавляется float (1+2) / 2 - средне арифметическое, чтобы усреднить для сортировки tom = doc.get('tom_s', None) if tom and isinstance(tom, unicode): tom = tom.strip().replace(u' ', u'') r = re_t1_t2.search(tom) if r: groups = r.groups() doc['tom_f'] = (int(groups[0]) + int(groups[1])) / 2.0 else: r = re_t1.search(tom) if r: doc['tom_f'] = float(r.groups()[0]) try: record_create_date = doc.get('record-create-date_dt', None) # print 'record_create_date1', record_create_date if record_create_date: doc['record-create-date_dts'] = record_create_date except Exception as e: print 'Error record-create-date_dt' holder_codes = _get_holdings(source_id=res[0]['source_id'], record_id=res[0]['record_id'], orgs_index=orgs_index, holdings_index=holdings_index, sources_index=sources_index) # if holder_codes: # print holder_codes if holder_codes: doc['system-holder_s'] = holder_codes org_types = set() for holder_code in holder_codes: org_type = orgs_index.get('code', {}).get(holder_code, {}).get('org_type', '') if org_type: org_types.add(org_type) if org_types: doc['org_type_s'] = list(org_types) doc['system-add-date_dt'] = res[0]['add_date'] doc['system-add-date_dts'] = res[0]['add_date'] doc['system-update-date_dt'] = res[0]['update_date'] doc['system-update-date_dts'] = res[0]['update_date'] doc['system-catalog_s'] = res[0]['source_id'] # doc['source-type_s'] = sources_index[res[0]['source_id']].source_type if str(doc['system-catalog_s']) == '2': full_text_file = None # doc['system-update-date_dt'] = res[0]['doc-id_s'] urls = doc.get('doc-id_s', None) if urls and type(urls) == list: for url in doc.get('doc-id_s', None): if url: full_text_file = url.split('/')[-1] else: if urls: full_text_file = urls.split('/')[-1] if full_text_file: text = full_text_extract(full_text_file) if text: doc['full-text'] = text docs.append(doc) i += 1 if i % 100 == 0: print 'indexed', i if len(docs) > 100: pass solr.add(docs) docs = list() res = rows.fetch_row(how=1) if docs: pass solr.add(docs) solr.commit() index_status.indexed = i # удаление records = [] if getattr(index_status, 'last_index_date', None): records = Record.objects.using('records').filter( deleted=True, update_date__gte=index_status.last_index_date).values('gen_id') else: records = Record.objects.using('records').filter(deleted=True).values( 'gen_id', 'update_date') record_gen_ids = [] for record in list(records): record_gen_ids.append(record['gen_id']) if record_gen_ids: solr.delete(record_gen_ids) solr.commit() index_status.deleted = len(record_gen_ids) index_status.last_index_date = start_index_date index_status.save() conn.query('DELETE FROM records WHERE deleted = 1') return True
def post(self, request): if not request.user.is_authenticated(): return redirect('login') # check if anonymous anonymous = request.POST.get('anonymous', '') thread_type = request.POST.get('thread_type', '') thread_type = 'complaint' if thread_type == '' or thread_type not in ['complaint', 'discussion']: raise Http404('invalid thread type') if thread_type == 'complaint': th_type = COMPLAINT elif thread_type == 'discussion': th_type = DISCUSSION else: th_type = COMPLAINT title = request.POST.get('title', '') content = request.POST.get('content', '') tags = request.POST.get('tags', '') ''' MULTIPLE FILES UPLOAD for afile in request.FILES.getlist('files'): File(file=afile, files=test).save() ''' if content == '': # or title=='' return redirect('index') #self.context['message'] = 'Title/content can\'t be empty' #return self.get(request, thread_type) # now with storage of the thread account = Account.objects.get(user=request.user) thread = Thread(thread_type=th_type, title=title, content=content, account=account) if anonymous == "yes": thread.anonymous = True else: thread.anonymous = False thread.save() # now the tags strtagids = request.POST.get('tagids', '') #return HttpResponse(strtagids) #tagids = list(map(lambda x: int(x),strtagids.split(','))) tagids = [] for x in strtagids.split(','): try: tagids.append(int(x)) except ValueError: pass if tagids == []: thread.tags.add( ThreadTag.objects.get(name__icontains='Not-Specified')) for tagid in tagids: thread.tags.add(ThreadTag.objects.get(pk=tagid)) thread.save() # now the targets strtargetids = request.POST.get('targetids', '') targetids = [] for x in strtargetids.split(','): try: targetids.append(int(x)) except ValueError: pass for tid in targetids: thread.targets.add(Target.objects.get(pk=tid)) if len(targetids) == 0: t = Target.objects.filter(name__icontains='udghos') if not len(t) == 0: thread.targets.add(t[0]) thread.save() images = request.FILES.getlist('images') for image in images: img = ThreadImage(name=image.name, thread=thread) img.save() img.image = image # to get pk of image object img.save() return redirect('index')
def display_table_list(request, app_name, table_name, embed=False): """ :param request: :param app_name: :param table_name: :param embed: 若此函数是被另一个view调用的,则embed=True,通常用在把kingadmin套件嵌入在其他项目时 :return: """ errors = [] if app_name in site.enabled_admins: # #print(enabled_admins[url]) if table_name in site.enabled_admins[app_name]: admin_class = site.enabled_admins[app_name][table_name] if request.method == "POST": # action 来了 print(request.POST) editable_data = request.POST.get("editable_data") if editable_data: # for list editable editable_data = json.loads(editable_data) #print("editable",editable_data) res_state, errors = batch_update(request, editable_data, admin_class) # if res_state == False: # #errors.append(error) else: # for action selected_ids = request.POST.get("selected_ids") action = request.POST.get("admin_action") if selected_ids: selected_objs = admin_class.model.objects.filter( id__in=selected_ids.split(',')) else: raise KeyError("No object selected.") if hasattr(admin_class, action): action_func = getattr(admin_class, action) request._admin_action = action return action_func(admin_class, request, selected_objs) querysets = tables.table_filter(request, admin_class, admin_class.model) searched_querysets = tables.search_by(request, querysets, admin_class) order_res = tables.get_orderby(request, searched_querysets, admin_class) paginator = Paginator(order_res[0], admin_class.list_per_page) page = request.GET.get('page') try: table_obj_list = paginator.page(page) except PageNotAnInteger: table_obj_list = paginator.page(1) except EmptyPage: table_obj_list = paginator.page(paginator.num_pages) table_obj = tables.TableHandler(request, admin_class.model, admin_class, table_obj_list, order_res) return_data = { 'table_obj': table_obj, 'app_name': app_name, 'paginator': paginator, 'errors': errors, 'enabled_admins': site.enabled_admins } if embed: return return_data else: return render(request, 'kingadmin/model_obj_list.html', return_data) else: raise Http404("url %s/%s not found" % (app_name, table_name))
def file_upload(request): if request.method == 'POST': f = request.FILES['file'] fname = handle_uploaded_file(f) return HttpResponse(fname) raise Http404()
def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist.") return render(request, 'polls/detail.html', {"question": question})
def get(self, request, *args, **kwargs): if not self.get_order_id(): raise Http404() return super(OrderSuccess, self).get(request, *args, **kwargs)
def quest_list(request, quest_id=None, submission_id=None, template="quest_manager/quests.html"): available_quests = [] in_progress_submissions = [] completed_submissions = [] past_submissions = [] draft_quests = [] available_tab_active = False in_progress_tab_active = False completed_tab_active = False past_tab_active = False drafts_tab_active = False remove_hidden = True active_quest_id = 0 active_submission_id = 0 # Figure out what tab we want. if quest_id is not None: # if a quest_id was provided, got to the Available tab active_quest_id = int(quest_id) available_tab_active = True elif submission_id is not None: # if sub_id was provided, figure out which tab and go there # this isn't active active_submission_id = int(submission_id) active_sub = get_object_or_404(QuestSubmission, pk=submission_id) if active_sub in in_progress_submissions: in_progress_tab_active = True elif active_sub in completed_submissions: completed_tab_active = True else: raise Http404("Couldn't find this Submission. Sorry!") # otherwise look at the path elif '/inprogress/' in request.path_info: in_progress_tab_active = True elif '/completed/' in request.path_info: completed_tab_active = True elif '/past/' in request.path_info: past_tab_active = True elif '/drafts/' in request.path_info: drafts_tab_active = True else: available_tab_active = True if '/all/' in request.path_info: remove_hidden = False page = request.GET.get('page') # need these anyway to count them. # get_available is not a queryset, cant use .count() if in_progress_tab_active: in_progress_submissions = QuestSubmission.objects.all_not_completed(request.user) in_progress_submissions = paginate(in_progress_submissions, page) # available_quests = [] elif completed_tab_active: completed_submissions = QuestSubmission.objects.all_completed(request.user) completed_submissions = paginate(completed_submissions, page) # available_quests = [] elif past_tab_active: past_submissions = QuestSubmission.objects.all_completed_past(request.user) past_submissions = paginate(past_submissions, page) # available_quests = [] elif drafts_tab_active: draft_quests = Quest.objects.all_drafts(request.user) else: if request.user.is_staff: available_quests = Quest.objects.all().visible().select_related('campaign', 'editor__profile') # num_available = available_quests.count() else: if request.user.profile.has_current_course: available_quests = Quest.objects.get_available(request.user, remove_hidden) # num_available = len(available_quests) else: available_quests = Quest.objects.get_available_without_course(request.user) # paginate or no? # available_quests = paginate(available_quests, page) # num_inprogress = QuestSubmission.objects.all_not_completed(request.user).count() # num_completed = QuestSubmission.objects.all_completed(request.user).count() context = { "heading": "Quests", "available_quests": available_quests, "remove_hidden": remove_hidden, # "num_available": num_available, "in_progress_submissions": in_progress_submissions, # "num_inprogress": num_inprogress, "completed_submissions": completed_submissions, "draft_quests": draft_quests, "past_submissions": past_submissions, # "num_completed": num_completed, "active_q_id": active_quest_id, "active_id": active_submission_id, "available_tab_active": available_tab_active, "inprogress_tab_active": in_progress_tab_active, "completed_tab_active": completed_tab_active, "past_tab_active": past_tab_active, "drafts_tab_active": drafts_tab_active, } return render(request, template, context)
def approve(request, submission_id): submission = get_object_or_404(QuestSubmission, pk=submission_id) origin_path = submission.get_absolute_url() if request.method == "POST": # currently only the big form has files. Need a more robust way to determine... if request.FILES or request.POST.get("awards"): if request.user.is_staff: form = SubmissionFormStaff(request.POST, request.FILES) else: form = SubmissionForm(request.POST, request.FILES) else: form = SubmissionQuickReplyForm(request.POST) if form.is_valid(): # handle badge assertion comment_text_addition = "" badge = form.cleaned_data.get('award') if badge: badges = [badge] else: badges = form.cleaned_data.get('awards') if badges: for badge in badges: # badge = get_object_or_404(Badge, pk=badge_id) new_assertion = BadgeAssertion.objects.create_assertion(submission.user, badge, request.user) messages.success(request, ("Badge " + str(new_assertion) + " granted to " + str(new_assertion.user))) comment_text_addition += "<p></br><i class='fa fa-certificate text-warning'></i> The <b>" + \ badge.name + "</b> badge was granted for this quest <i class='fa fa-certificate text-warning'></i></p>" # handle with quest comments blank_comment_text = "" if 'approve_button' in request.POST: note_verb = "approved" icon = "<span class='fa-stack'>" + \ "<i class='fa fa-check fa-stack-2x text-success'></i>" + \ "<i class='fa fa-shield fa-stack-1x'></i>" + \ "</span>" blank_comment_text = "(approved without comment)" submission.mark_approved() ############## elif 'comment_button' in request.POST: note_verb = "commented on" icon = "<span class='fa-stack'>" + \ "<i class='fa fa-shield fa-stack-1x'></i>" + \ "<i class='fa fa-comment-o fa-stack-2x text-info'></i>" + \ "</span>" blank_comment_text = "(no comment added)" elif 'return_button' in request.POST: note_verb = "returned" icon = "<span class='fa-stack'>" + \ "<i class='fa fa-shield fa-stack-1x'></i>" + \ "<i class='fa fa-ban fa-stack-2x text-danger'></i>" + \ "</span>" blank_comment_text = "(returned without comment)" submission.mark_returned() ############## else: raise Http404("unrecognized submit button") comment_text_form = form.cleaned_data.get('comment_text') if not comment_text_form: comment_text = blank_comment_text else: comment_text = comment_text_form comment_new = Comment.objects.create_comment( user=request.user, path=origin_path, text=comment_text + comment_text_addition, target=submission ) # handle files if request.FILES: file_list = request.FILES.getlist('files') for afile in file_list: # print(afile) newdoc = Document(docfile=afile, comment=comment_new) newdoc.save() # don't say "with" in notification if no comment was entered if not comment_text_form: action = None else: action = comment_new affected_users = [submission.user, ] notify.send( request.user, action=action, target=submission, recipient=submission.user, affected_users=affected_users, verb=note_verb, icon=icon, ) message_string = "<a href='" + origin_path + "'>Submission of " + \ submission.quest.name + "</a> " + note_verb + \ " for <a href='" + submission.user.profile.get_absolute_url() + "'>" + submission.user.username + "</a>" messages.success(request, message_string) return redirect("quests:approvals") else: # messages.error(request, "There was an error with your comment. Maybe you need to type something?") # return redirect(origin_path) # rendering here with the context allows validation errors to be displayed context = { "heading": submission.quest.name, "submission": submission, # "comments": comments, "submission_form": form, "anchor": "submission-form-" + str(submission.quest.id), # "reply_comment_form": reply_comment_form, } return render(request, 'quest_manager/submission.html', context) else: raise Http404
def get(self, request, pub_id): obj = get_object_or_404(Publication, id=pub_id) if not obj.user == request.user and not request.user.groups.filter(name='supervisor').exists(): raise Http404() return render(request, 'publications/view_v2.html', {'publication': obj, 'can_change': obj.user == request.user})
def ks_info(request, offset): try: offset = str(offset) except: raise Http404() # ks_list = ['ahks', 'bjks', 'fjks', 'gsks', 'gxks', 'hbks', 'hebks', 'jsks', 'jxks', 'nmks', 'shks', 'tjks'] # ks_detail = [] # ans = 0 # ks_select_list = { # 'ahks' : models.KSinfo_ahks.objects.all(), # 'bjks' : models.KSinfo_bjks.objects.all(), # 'fjks' : models.KSinfo_fjks.objects.all(), # 'gsks' : models.KSinfo_gsks.objects.all(), # 'gxks' : models.KSinfo_gxks.objects.all(), # 'hbks' : models.KSinfo_hbks.objects.all(), # 'hebks' : models.KSinfo_hebks.objects.all(), # 'jsks' : models.KSinfo_jsks.objects.all(), # 'jxks' : models.KSinfo_jxks.objects.all(), # 'nmks' : models.KSinfo_nmks.objects.all(), # 'shks' : models.KSinfo_shks.objects.all(), # 'tjks' : models.KSinfo_tjks.objects.all(), # } # ks_select = ks_select_list.get(offset, 'nothing')() ks_infor_list = { 'ahks': {"ks_info_ah": models.KSinfo_ahks.objects.all()}, 'bjks': {"ks_info_bj": models.KSinfo_bjks.objects.all()}, 'fjks': {"ks_info_fj": models.KSinfo_fjks.objects.all()}, 'gsks': {"ks_info_gs": models.KSinfo_gsks.objects.all()}, 'gxks': {"ks_info_gx": models.KSinfo_gxks.objects.all()}, 'hbks': {"ks_info_hb": models.KSinfo_hbks.objects.all()}, 'hebks': {"ks_info_heb": models.KSinfo_hebks.objects.all()}, 'jsks': {"ks_info_js": models.KSinfo_jsks.objects.all()}, 'jxks': {"ks_info_jx": models.KSinfo_jxks.objects.all()}, 'nmks': {"ks_info_nm": models.KSinfo_nmks.objects.all()}, 'shks': {"ks_info_sh": models.KSinfo_shks.objects.all()}, 'tjks': {"ks_info_tj": models.KSinfo_tjks.objects.all()}, } # ks_info_list = { # 'ahks': {"ks_info_ah": ks_select}, # "ks_info_bj": ks_select, # "ks_info_gj": ks_select, # "ks_info_gs": ks_select, # "ks_info_gx": ks_select, # "ks_info_hb": ks_select, # "ks_info_heb": ks_select, # "ks_info_js": ks_select, # "ks_info_jx": ks_select, # "ks_info_nm": ks_select, # "ks_info_sh": ks_select, # "ks_info_tj": ks_select, # } ks_info = ks_infor_list.get(offset, "nothing") # html = "<div class='title'><div class='info'><table border='1'><thead><th>期数</th><th>形态</th><th>和值</th><th>大小</th><th>单双</th></thead><tbody>{% for line in ks_info %}<tr><td>{{ line.date }}</td><td>{{ line.status }}</td><td>{{ line.hezhi }}</td><td>{{ line.BigS }}</td><td>{{ line.SigD }}</td></tr>{% endfor %}</tbody></table></div></div>" # html_name = offset+".html" return render(request, html_name, ks_info)
def my_posts(request): if request.user.is_authenticated: if request.user.profile.is_author: posts = Post.objects.filter(author=request.user) return render(request, 'myposts.html', {'posts': posts}) return Http404()
def profile(request): if request.user.is_authenticated: return render(request, "profile.html") else: return Http404() # TODO: Render a more gentle page.
def get_object(self): try: wishlist = WishList.objects.get(user=self.request.user) return wishlist except ObjectDoesNotExist: raise Http404("You do not have an active wishlist")
def detail(request,trip_id): try: trip = Trip.objects.get(pk = trip_id) except Trip.DoesNotExist: raise Http404("Album does not exist") return render(request,'tour/detail.html', {'trip' : trip})
def complete(request, submission_id): submission = get_object_or_404(QuestSubmission, pk=submission_id) origin_path = submission.get_absolute_url() # http://stackoverflow.com/questions/22470637/django-show-validationerror-in-template if request.method == "POST": # for some reason Summernote is submitting the form in the background when an image is added or # dropped into the widget We need to ignore that submission # https://github.com/summernote/django-summernote/issues/362 if 'complete' not in request.POST and 'comment' not in request.POST: raise Http404("unrecognized submit button") # form = CommentForm(request.POST or None, wysiwyg=True, label="") # form = SubmissionQuickReplyForm(request.POST) form = SubmissionForm(request.POST, request.FILES) if form.is_valid(): comment_text = form.cleaned_data.get('comment_text') if not comment_text: if submission.quest.verification_required and not request.FILES: messages.error(request, "Please read the Submission Instructions more carefully. " "You are expected to attach something or comment to complete this quest!") return redirect(origin_path) else: comment_text = "(submitted without comment)" comment_new = Comment.objects.create_comment( user=request.user, path=origin_path, text=comment_text, target=submission, ) if request.FILES: file_list = request.FILES.getlist('files') for afile in file_list: newdoc = Document(docfile=afile, comment=comment_new) newdoc.save() if 'complete' in request.POST: note_verb = "completed" if submission.quest.verification_required: note_verb += ", awaiting approval." else: note_verb += " and automatically approved." icon = "<i class='fa fa-shield fa-lg'></i>" # Notify teacher if they are specific to quest but are not the student's teacher if submission.quest.specific_teacher_to_notify \ and submission.quest.specific_teacher_to_notify not in request.user.profile.current_teachers(): affected_users = [submission.quest.specific_teacher_to_notify, ] else: affected_users = None submission.mark_completed() ################### if not submission.quest.verification_required: submission.mark_approved() elif 'comment' in request.POST: note_verb = "commented on" icon = "<span class='fa-stack'>" + \ "<i class='fa fa-shield fa-stack-1x'></i>" + \ "<i class='fa fa-comment-o fa-stack-2x text-info'></i>" + \ "</span>" affected_users = [] if request.user.is_staff: affected_users = [submission.user, ] else: # student comment # student's teachers affected_users.extend(request.user.profile.current_teachers()) # User.objects.filter(is_staff=True) # add quest's teacher if necessary if submission.quest.specific_teacher_to_notify: affected_users.append(submission.quest.specific_teacher_to_notify) # remove doubles/flatten affected_users = set(affected_users) else: raise Http404("unrecognized submit button") notify.send( request.user, action=comment_new, target=submission, recipient=submission.user, affected_users=affected_users, verb=note_verb, icon=icon, ) messages.success(request, ("Quest " + note_verb)) return redirect("quests:quests") else: context = { "heading": submission.quest.name, "submission": submission, # "comments": comments, "submission_form": form, "anchor": "submission-form-" + str(submission.quest.id), # "reply_comment_form": reply_comment_form, } return render(request, 'quest_manager/submission.html', context) else: raise Http404
def post_delete(request, slug): if not request.user.is_authenticated(): return Http404() post = get_object_or_404(Post, slug=slug) post.delete() return redirect('post:index')
def post(self, request, election, position): election = get_object_or_404(Election, codename=election) position = get_object_or_404(Position, codename=position) if not is_voting_current(election): raise Http404() # check if the user has already voted for the position if Voter.objects.filter(username=request.user.username, position=position): messages.error( request, 'You have already voted for {} in {}'.format( position.name, election.name)) return redirect( to=reverse('election:position', args=[election.codename, position.codename])) nominations_rank = dict.fromkeys([ str(nomination.uuid) for nomination in position.nomination_set.all() ]) ranks = set(map(str, (range(1, len(nominations_rank) + 2)))) # check if ranks are valid and unique, check if ron in has a valid rank has_ron = False for k, v in request.POST.items(): if k == 'ron': if v in ranks: ranks.remove(v) has_ron = True else: messages.error( request, 'Error. Your vote has not been recorded for {} in {}'. format(position.name, election.name)) return redirect(to=reverse( 'election:position', args=[election.codename, position.codename])) elif k in nominations_rank: if v in ranks: nominations_rank[k] = int(v) ranks.remove(v) else: messages.error( request, 'Error. Your vote has not been recorded for {} in {}'. format(position.name, election.name)) return redirect(to=reverse( 'election:position', args=[election.codename, position.codename])) if not has_ron: messages.error( request, 'Error. Your vote has not been recorded for {} in {}'.format( position.name, election.name)) return redirect( to=reverse('election:position', args=[election.codename, position.codename])) # check if all nominations for the position has a rank for _, v in nominations_rank.items(): if v == None: messages.error( request, 'Error. Your vote has not been recorded for {} in {}'. format(position.name, election.name)) return redirect( to=reverse('election:position', args=[election.codename, position.codename])) with transaction.atomic(): Voter(username=request.user.username, position=position).save() vote = Vote(position=position) vote.save() for k, v in nominations_rank.items(): nomination = Nomination.objects.get(uuid=k) VoteRecord(vote=vote, nomination=nomination, rank=v).save() messages.success( request, 'Your vote for {} in {} has been recorded'.format( position.name, election.name)) return redirect(to=reverse( 'election:position', args=[election.codename, position.codename]))
def handle_cms_response(response): if response.status_code == 404: raise Http404() response.raise_for_status() return response.json()
def get_object(self, *args, **kwargs): slug = self.kwargs.get('slug') instance = get_object_or_404(Post, slug=slug) if instance is None: raise Http404("Post doesn't exists") return instance
def display_table_list(request, app_name, table_name): errors = [] if app_name in site.enabled_admins: ##print(enabled_admins[url]) if table_name in site.enabled_admins[app_name]: admin_class = site.enabled_admins[app_name][table_name] if request.method == "POST": # action 来了 print(request.POST) editable_data = request.POST.get("editable_data") if editable_data: #for list editable editable_data = json.loads(editable_data) #print("editable",editable_data) res_state, error = batch_update(request, editable_data, admin_class) if res_state == False: errors.append(error) else: #for action selected_ids = request.POST.get("selected_ids") action = request.POST.get("admin_action") if selected_ids: selected_objs = admin_class.model.objects.filter( id__in=selected_ids.split(',')) else: raise KeyError("No object selected.") if hasattr(admin_class, action): action_func = getattr(admin_class, action) request._admin_action = action return action_func(admin_class, request, selected_objs) if request.method == "POST2": #drepcated #print('post-->', request.POST) delete_tag = request.POST.get("_delete_confirm") if delete_tag == "yes": del_ids = request.POST.getlist("deleted_objs") admin_class.model.objects.filter(id__in=del_ids).delete() else: admin_action = request.POST.get('admin_action') selected_raw_ids = request.POST.get('selected_ids', '') selected_ids = selected_raw_ids.split(',') selected_objs = admin_class.model.objects.filter( id__in=selected_ids) if hasattr(admin_class, admin_action): admin_action_func = getattr(admin_class, admin_action) return admin_action_func(admin_class, request, selected_objs) else: raise NotImplementedError( "admin_action %s cannot find" % admin_action) querysets = tables.table_filter(request, admin_class, admin_class.model) searched_querysets = tables.search_by(request, querysets, admin_class) order_res = tables.get_orderby(request, searched_querysets, admin_class) paginator = Paginator(order_res[0], admin_class.list_per_page) page = request.GET.get('page') try: table_obj_list = paginator.page(page) except PageNotAnInteger: table_obj_list = paginator.page(1) except EmptyPage: table_obj_list = paginator.page(paginator.num_pages) table_obj = tables.TableHandler(request, admin_class.model, admin_class, table_obj_list, order_res) return render( request, 'kingadmin/model_obj_list.html', { 'table_obj': table_obj, 'app_name': app_name, 'active_url': '/kingadmin/', 'paginator': paginator, 'errors': errors }) else: raise Http404("url %s/%s not found" % (app_name, table_name))
def Sanitation(request): try: sanitation_cols = [ 'toiletb_func', 'urinals_b', 'toiletg_func', 'urinals_g' ] # these 2 attributes are yet to be considered extra = ['toiletwater_b', 'toiletwater_g'] # dist_weight contain key as district and value as its overall count of toilets dist_weight = dict() # Get districts shape district = state_maharashtra.objects.all().order_by('district') # serialize the data district_serialize = serialize('geojson', district, geometry_field='geom', fields=('district', )) # create a dictionary dist_json = json.loads(district_serialize) # remove crs field dist_json.pop('crs', None) for i in range(len(district)): d_name = dist_json['features'][i]['properties']['district'] # vals_dict contains all 4 attributes and handwash_yn and their total for the particular district vals_dict = dict() for col in sanitation_cols: vals = [ x.get(col) for x in SchoolInfo.objects.values(col).filter( distname__iexact=d_name) ] sum_of_vals = sum([int(x) for x in vals]) vals_dict.update({col: sum_of_vals}) # for handwash_yn, 1 = yes and 2 = no. so considering sum of total 1s vals_dict['handwash_yn'] = SchoolInfo.objects.values('handwash_yn').annotate(Count('handwash_yn')).\ filter(distname__iexact=d_name).order_by('handwash_yn')[0].get('handwash_yn__count') dist_weight.update({d_name: sum(vals_dict.values())}) dist_json['features'][i]['properties']['feature_val'] = sum( vals_dict.values()) range_value = max(dist_weight.values()) - min(dist_weight.values()) district = json.dumps(dist_json) grade = [ round(float(i * range_value) / 100, 2) for i in range(0, 110, 20) ] dark_blue = Color('#F0DC82') light_blue = Color('#8A3324') color_list = list(str(i) for i in light_blue.range_to(dark_blue, 5)) feature = "Sanitation" return render_to_response( 'chloropleth/maps.html', { 'district': district, 'Name': str(feature), 'range': range_value, 'grade': grade, 'color': color_list }) except IndexError: raise Http404('Nope')
def table_add(request, app_name, table_name): #print("request :",request.POST) if app_name in site.enabled_admins: if table_name in site.enabled_admins[app_name]: fields = [] admin_class = site.enabled_admins[app_name][table_name] for field_obj in admin_class.model._meta.fields: if field_obj.editable: fields.append(field_obj.name) for field_obj in admin_class.model._meta.many_to_many: fields.append(field_obj.name) if admin_class.add_form == None: model_form = forms.create_form(admin_class.model, fields, admin_class, form_create=True, request=request) else: #this admin has customized creation form defined model_form = admin_class.add_form if request.method == "GET": form_obj = model_form() elif request.method == "POST": form_obj = model_form(request.POST) if form_obj.is_valid(): form_obj.validate_unique() if form_obj.is_valid(): print("add form valid", form_obj.cleaned_data) form_obj.save() if request.POST.get('_continue') is not None: redirect_url = '%s/%s/' % (re.sub( "add/$", "change", request.path), form_obj.instance.id) #print('redirect url',redirect_url) return redirect(redirect_url) elif request.POST.get("_add_another") is not None: #print('add another form', form_obj) form_obj = model_form() else: #return to table list page if "_popup=1" not in request.get_full_path(): redirect_url = request.path.rstrip("/add/") return redirect(redirect_url) else: print("pop up add windows....") return render( request, 'kingadmin/table_add.html', { 'form_obj': form_obj, 'model_name': admin_class.model._meta.model_name, 'model_verbose_name': admin_class.model._meta.verbose_name, 'model_db_table': admin_class.model._meta.db_table, 'admin_class': admin_class, 'app_name': app_name, #'active_url': '/kingadmin/', 'enabled_admins': site.enabled_admins }) else: raise Http404("url %s/%s not found" % (app_name, table_name))
def Security(request): try: # for reference labels = [ 'Not Applicable', 'Pucca', 'Pucca but broken', 'barbed wire fencing', 'Hedges', 'No boundary wall', 'others', 'Partial', 'Under Construction' ] # weights corresponds to the labels above weights = ['', 0.1, 0.6, 0.4, 0.8, 0.7, 0, 0.3, 0.5, 0.2] # dist_weight contain key as district and value as its overall weighted average of bndry walls dist_weight = dict() district = state_maharashtra.objects.all().order_by('district') # serialize the data district_serialize = serialize('geojson', district, geometry_field='geom', fields=('district', )) # create a dictionary dist_json = json.loads(district_serialize) # remove crs field dist_json.pop('crs', None) for i in range(len(district)): d_name = dist_json['features'][i]['properties']['district'] bndry_info = SchoolInfo.objects.values('bndrywall'). \ annotate(Count('bndrywall')).filter(distname__iexact=d_name).order_by('bndrywall') # vals_dict contains (total count of labels[i])*weights[i] for the particular district vals_dict = list() for x in bndry_info: vals_dict.append(weights[int(x.get('bndrywall'))] * x.get('bndrywall__count')) dist_weight.update( {d_name: round(sum(vals_dict) / len(vals_dict), 2)}) dist_json['features'][i]['properties']['feature_val'] = round( float(sum(vals_dict)) / len(vals_dict), 2) range_value = max(dist_weight.values()) - min(dist_weight.values()) district = json.dumps(dist_json) grade = [ round(float(i * range_value) / 100, 2) for i in range(0, 110, 20) ] dark_blue = Color('#FAE6FA') light_blue = Color('#9F00C5') color_list = list(str(i) for i in light_blue.range_to(dark_blue, 5)) feature = "Security" return render_to_response( 'chloropleth/maps.html', { 'district': district, 'Name': str(feature), 'range': range_value, 'grade': grade, 'color': color_list }) except IndexError, e: print str(e) raise Http404('Nope')
def dispatch(self, request, *args, **kwargs): op = self.get_object() if op.author != self.request.user: raise Http404("You are not allowed to delete this Post") return super(PostDeleteView, self).dispatch(request, *args, **kwargs)
def Water(request): try: dark_blue = Color('darkblue') light_blue = Color('lightblue') color_list = list(str(i) for i in light_blue.range_to(dark_blue, 5)) #Get districts shape district = state_maharashtra.objects.all().order_by('district') # serialize the data district_serialize = serialize('geojson', district, geometry_field='geom', fields=('district', )) # create a dictionary dist_json = json.loads(district_serialize) # remove crs field dist_json.pop('crs', None) max_v = 0 min_v = 1000 weights = ['', 0, 0, 0, 1, 0] for i in range(len(district)): d_name = dist_json['features'][i]['properties']['district'] water_info = SchoolInfo.objects.values('water').annotate( Count('water')).filter( distname__iexact=d_name).order_by('water') weighted_values = list() for x in water_info: if (x.get('water')) is not None: if (int(x.get('water')) == 9): continue weighted_values.append( round(weights[int(x.get('water'))] * x.get('water__count'), 3)) temp = round(sum(weighted_values) / len(weighted_values), 2) if (temp > max_v): max_v = temp if (temp < min_v): min_v = temp dist_json['features'][i]['properties']['feature_val'] = temp district = json.dumps(dist_json) range_value = max_v - min_v feature = "Drinking Water" grade = [ round(float(i * range_value) / 100, 2) for i in range(0, 110, 20) ] return render_to_response( 'chloropleth/maps.html', { 'district': district, 'Name': str(feature), 'range': range_value, 'grade': grade, 'color': color_list }) except IndexError, e: raise Http404("Nope")
def local_records_indexing(request): slug = 'local_records' try: solr_address = settings.SOLR['local_records_host'] db_conf = settings.DATABASES.get('local_records') except KeyError: raise Http404(u'Catalog not founded') if not db_conf: raise Exception( u'Settings not have inforamation about database, where contains records.' ) if db_conf['ENGINE'] != 'django.db.backends.mysql': raise Exception( u' Support only Mysql Database where contains records.') try: conn = MySQLdb.connect(host=db_conf['HOST'], user=db_conf['USER'], passwd=db_conf['PASSWORD'], db=db_conf['NAME'], port=int(db_conf['PORT']), charset='utf8', use_unicode=True, cursorclass=MySQLdb.cursors.SSDictCursor) except MySQLdb.OperationalError as e: conn = MySQLdb.connect(unix_socket=db_conf['HOST'], user=db_conf['USER'], passwd=db_conf['PASSWORD'], db=db_conf['NAME'], port=int(db_conf['PORT']), charset='utf8', use_unicode=True, cursorclass=MySQLdb.cursors.SSDictCursor) print 'indexing start', try: index_status = IndexStatus.objects.get(catalog=slug) except IndexStatus.DoesNotExist: index_status = IndexStatus(catalog=slug) if not getattr(index_status, 'last_index_date', None): select_query = "SELECT * FROM records where deleted = 0 and content != NULL" else: select_query = "SELECT * FROM records where update_date >= '%s' and deleted = 0 and content != NULL" % ( str(index_status.last_index_date)) print 'records finded', solr = sunburnt.SolrInterface( solr_address, http_connection=httplib2.Http(disable_ssl_certificate_validation=True)) docs = list() start_index_date = datetime.datetime.now() conn.query(select_query) rows = conn.use_result() res = rows.fetch_row(how=1) print 'records fetched', i = 0 while res: content = zlib.decompress(res[0]['content'], -15).decode('utf-8') doc_tree = etree.XML(content) doc_tree = xslt_indexing_transformer(doc_tree) doc = doc_tree_to_dict(doc_tree) doc = add_sort_fields(doc) # для сортировки по тому, извлекаем строку содержащую номер тома или промежуток и посещаем резултат вычисления # в поле tom_f, которое в последствии сортируется # если трока типа т.1 то в том добавляется float 1 # если строка содержит т.1-2 то добавляется float (1+2) / 2 - средне арифметическое, чтобы усреднить для сортировки tom = doc.get('tom_s', None) if tom and isinstance(tom, unicode): tom = tom.strip().replace(u' ', u'') r = re_t1_t2.search(tom) if r: groups = r.groups() doc['tom_f'] = (int(groups[0]) + int(groups[1])) / 2.0 else: r = re_t1.search(tom) if r: doc['tom_f'] = float(r.groups()[0]) try: record_create_date = doc.get('record-create-date_dt', None) # print 'record_create_date1', record_create_date if record_create_date: doc['record-create-date_dts'] = record_create_date except Exception as e: print 'Error record-create-date_dt', e.message doc['system-add-date_dt'] = res[0]['add_date'] doc['system-add-date_dts'] = res[0]['add_date'] doc['system-update-date_dt'] = res[0]['update_date'] doc['system-update-date_dts'] = res[0]['update_date'] doc['system-catalog_s'] = res[0]['source_id'] if str(doc['system-catalog_s']) == '2': full_text_file = None # doc['system-update-date_dt'] = res[0]['doc-id_s'] urls = doc.get('doc-id_s', None) if urls and type(urls) == list: for url in doc.get('doc-id_s', None): if url: full_text_file = url.split('/')[-1] else: if urls: full_text_file = urls.split('/')[-1] if full_text_file: text = full_text_extract(full_text_file) if text: doc['full-text'] = text docs.append(doc) i += 1 if len(docs) > 25: solr.add(docs) print i docs = list() res = rows.fetch_row(how=1) if docs: solr.add(docs) solr.commit() index_status.indexed = i # удаление records = [] if getattr(index_status, 'last_index_date', None): records = Record.objects.using('records').filter( deleted=True, update_date__gte=index_status.last_index_date).values('gen_id') else: records = Record.objects.using('records').filter(deleted=True).values( 'gen_id', 'update_date') record_gen_ids = [] for record in list(records): record_gen_ids.append(record['gen_id']) if record_gen_ids: solr.delete(record_gen_ids) solr.commit() index_status.deleted = len(record_gen_ids) index_status.last_index_date = start_index_date index_status.save() conn.query('DELETE FROM records WHERE deleted = 1') return True
def wrapper(request, *args, **kwargs): if request.user.is_staff: return viewfunc(request, *args, **kwargs) else: raise Http404()
def get(self, request, *args, **kwargs): added_product = [] context = {} products = [] total_price = "0" count = 0 static_cookie = ["csrftoken", "sessionid", "messages"] for cookie in request.COOKIES: if cookie not in static_cookie: instance = request.COOKIES[cookie].split(',') if not Product.objects.filter(id=int(instance[0])).exists( ) or not instance[1].isnumeric() or int(instance[1]) > 3: raise Http404( f'You added "{cookie}" to cookie, Invalid Cookie.') else: count += 1 product = Product.objects.filter(id=instance[0]).first() name = product.name final_price = product.final_price int_price = int(final_price.replace(",", "")) * int( instance[1]) price = '{0:,}'.format(int_price) total_price = int(total_price.replace(",", "")) + int_price total_price = '{0:,}'.format(total_price) # add cookie to cartitem > login user if request.user.is_authenticated: if not Cart.objects.filter(user=request.user, checkout=False).exists(): cart = Cart.objects.create(user=request.user, checkout=False) cart = Cart.objects.filter(user=request.user, checkout=False).first() if not CartItem.objects.filter(product=product, cart=cart): cartitem = CartItem.objects.create( product=product, cart=cart, quantity=instance[1], price=price, ) else: cartitem = CartItem.objects.filter( product=product, cart=cart).first() cartitem.quantity = instance[1] cartitem.price = price cartitem.save() added_product.append(product) products.append({ 'product': product, # product query 'quantity': instance[1], # quantity in cookie 'price': price, # product.price * quantity }) # this part checks item cart that if not in cookie if request.user.is_authenticated: for item in CartItem.objects.filter(cart=cart): if item.product not in added_product: product = Product.objects.filter(name=item.product).first() total_price = int(total_price.replace(",", "")) + int( item.price.replace(",", "")) total_price = '{0:,}'.format(total_price) products.append({ 'product': product, 'quantity': item.quantity, 'price': item.price, }) if count == 0: context = {"empty": True} return render(request, self.template_name, context) context["total_price"] = total_price context["products"] = products return render(request, self.template_name, context)
def form_values_bank(request, product_id, user_id): duration = Duration.objects.all() banks = Bank.objects.all() product = Product.objects.get(pk=product_id) print(product) ted = 0.0 tem = 0.0 cuota = 0.0 fvp = 0.0 total = 0.0 cuotaOne = 0.0 list_coutas = [] list_cuotasNumber = [] row_data = [] row_projection = [] cuotaTwo = 0.0 try: if request.method == 'POST': duration = Duration.objects.all() object_user = User.objects.get(pk=user_id) object_user_id = object_user.id user_id = object_user_id print(object_user.id) #passenger_id = int(request.POST["passenger"]) amount = int(request.POST["amount"]) duration_id = int(request.POST["duration"]) bank_id = request.POST["bank"] now = datetime.datetime.now() print(amount) print(duration_id) print(bank_id) print(now) product = Product.objects.get(pk=product_id) producType_id = product.productType.id object_projectionType = ProjectionType.objects.get( productType_id=producType_id) object_varibleOne = VariableEconomic.objects.get( bank_id=bank_id, duration_id=duration_id) object_duration = Duration.objects.get(id=duration_id) object_varible_id = object_varibleOne.id print(object_duration.limite_superior) months = int(object_duration.limite_superior / 30) print(months) p = Projection(type_of_projection=object_projectionType, amount=amount, date_modified=now, user=object_user, variableEconomic=object_varibleOne) p.save() if object_projectionType.name == 'Proyección credito de consumo': tem = math.pow((1 + object_varibleOne.value), 1 / 12) - 1 ted = math.pow((1 + tem), 1 / 30) - 1 b = 0.0 cuota = 0.0 fvp = 0.0 row_data = [] row_projection = [] numerCuota = 0 for i in range(months): a = i + 1 * 30 b = b + a c = 1 / math.pow((1 + ted), a) fvp = fvp + c numberCuota = 1 + i cuota = amount / fvp cuotaOne = round(cuota, 3) row_data.append(numberCuota) row_data.append(cuotaOne) row_projection.append(row_data) list_coutas = [] cuotaTwo = round(cuota, 3) total = 0.0 total = cuota * months else: tem = math.pow((1 + object_varibleOne.value), 1 / 12) - 1 ted = math.pow((1 + tem), 1 / 30) - 1 b = 0.0 cuota = 0.0 fvp = 0.0 row_data = [] row_projection = [] numerCuota = 0 for i in range(months): a = i + 1 * 30 b = b + a c = 1 / math.pow((1 + ted), a) fvp = fvp + c numberCuota = 1 + i cuota = amount / fvp cuotaOne = round(cuota, 3) row_data.append(numberCuota) row_data.append(cuotaOne) row_projection.append(row_data) list_coutas = [] cuotaTwo = round(cuota, 3) total = 0.0 total = cuota * months total = total * 0.90 context = { "p": p, "ted": ted, "tem": tem, "cuota": cuota, "months": months, "fvp": fvp, "total": total, "object_user": object_user, "user_id": user_id, "list_coutas": list_coutas, "cuotaOne": cuotaOne, "list_cuotasNumber": list_cuotasNumber, "row_data ": row_data, "row_projection": row_projection, "cuotaTwo": cuotaTwo, "amount": amount, } return render(request, 'pointofequilibrium/cdt.html', context) except Product.DoesNotExist: raise Http404("Product does not exist") context = { "p": p, "ted": ted, "tem": tem, "cuota": cuota, "months": months, "fvp": fvp, "total": total, "object_user": object_user, "user_id": user_id, "list_coutas": list_coutas, "cuotaOne": cuotaOne, "list_cuotasNumber": list_cuotasNumber, "row_data ": row_data, "row_projection": row_projection, "cuotaTwo": cuotaTwo, "amount": amount, } return render(request, 'pointofequilibrium/projection.html', context)