def runtests(request, testrun_id): # force the CSRF cookie to be set # @@@ replace with ensure_csrf_cookie decorator in Django 1.4 get_token(request) testrun = TestRunList.get_by_id(testrun_id, auth=request.auth) if not testrun.environmentgroups_prefetch.match(request.environments): return redirect("runtests_environment", testrun_id=testrun_id) cycle = testrun.testCycle product = cycle.product # for prepopulating finder cycles = ( TestCycleList.ours(auth=request.auth).sort("name", "asc").filter(product=product, status=TestCycleStatus.ACTIVE) ) runs = TestRunList.ours(auth=request.auth).sort("name", "asc").filter(testCycle=cycle, status=TestRunStatus.ACTIVE) return TemplateResponse( request, "runtests/run.html", { "product": product, "cycle": cycle, "testrun": testrun, "cases": TestRunIncludedTestCaseList.get(auth=request.auth).filter(testRun=testrun), "finder": {"cycles": cycles, "runs": runs}, }, )
def main(request): """Main listing.""" get_token(request) posts = Post.objects.all().order_by("-created") paginator = Paginator(posts, 5) try: page = int(request.GET.get("page", '1')) except ValueError: page = 1 try: posts = paginator.page(page) except (InvalidPage, EmptyPage): posts = paginator.page(paginator.num_pages) if request.user.is_authenticated(): user = request.user else: user = User.objects.get(username='******') context = { 'posts':posts, 'user':user, 'post_list':posts.object_list, 'months':mkmonth_lst(), 'STATIC_URL' : settings.STATIC_URL } context.update(csrf(request)) return render_to_response('blog/list.html', context)
def functionRegister(request): if request.method == 'POST': userform = UserCreationForm(request.POST, prefix='user') if userform.is_valid(): userform.save() return HttpResponseRedirect('/') else: context = { 'userform' : userform, 'csrf_token' : csrf.get_token(request) } response = render_to_string('registration/register.html', context) return HttpResponse(response) elif request.method == 'GET': userform = UserCreationForm(prefix='user') context = { 'userform' : userform, 'csrf_token' : csrf.get_token(request) } response = render_to_string('registration/register.html', context) return HttpResponse(response) else: return HttpResponse("Bad request!")
def detail(request, poll_id): get_token(request) # m=MongoDb() # return HttpResponse("You're looking at poll %s." % poll_id) # latest_poll_list=m.db.logs.find({}) # latest_poll_list = LogMsg.objects.all()#.order_by('-deviceId')[:5] # l=logs(deviceId='00fe00898989',data='hi at '+str(time.time())) # l.save() #~ devices_list = logs.objects.values('deviceId') #~ devices_list=devices_list.sort() #~ latest_poll_list = logs.objects.all()#.order_by('-deviceId')[:5] #~ latest_poll_list = logs.objects(data='myNewMsg') #~ devices_list = logs.objects.distinct('deviceId') #~ devices_list.sort() devices_list = Device.objects.all() devices_list=list(devices_list) devices_list=[Device(deviceId=AllDevicesId,lastActivityTime=min([x.lastActivityTime for x in devices_list]))]+devices_list latest_poll_list = logs.objects(deviceId=poll_id).order_by('+time') #~ print 'formattedTime',latest_poll_list[-1].formattedTime return render_to_response('polls/logList.html', { 'latest_poll_list': latest_poll_list, 'devices_list':devices_list, 'error_message':'', })
def process_response(self, request, response): """will set csrf cookie to all responses""" # these two calls make the csrf token cookie to be installed # properly on the response, see implementation of those calls # to see why this works and why get_token is necessary get_token(request) return super(CsrfViewMiddleware, self).process_response(request, response)
def collection(request): ren = None if request.method == "POST": curr.execute("delete from reader_user_token where token=(%s)", (get_token(request),)) conn.commit() rotate_token(request) else: if request.method == "GET": curr.execute("select user_id from reader_user_token where token=(%s)", (get_token(request),)) if curr.rowcount == 1: curr.execute("update reader_user_token set last_use=(select clock_timestamp()) where token=(%s)", (get_token(request),)) conn.commit() curr.execute("""select user_email from reader_user where id = (select user_id from reader_user_token where token=(%s))""", (get_token(request),)) content = {"email" : curr.fetchone()[0]} curr.execute("select id, title, url, favicon, is_active from reader_site where user_id = (select user_id from reader_user_token where token=(%s)) order by id", (get_token(request),)) rows = curr.fetchall() rowarray = [] for row in rows: d = collections.OrderedDict() d['id'] = row[0] if row[1] is None: d['title'] = "" else: d['title'] = row[1] d['url'] = row[2] dd = row[2].split('/') d['favicon'] = row[3] or (('http://' + dd[0] if dd[0] != 'http:' else dd[0] + '//' + dd[2]) + '/favicon.ico') d['is_active'] = row[4] rowarray.append(d) content.update({"sites" : rowarray}) ren = render(request, 'collection.html', content) if ren is None: ren = redirect('index') return ren
def test_login_csrf_rotate(self, password='******'): """ Makes sure that a login rotates the currently-used CSRF token. """ # Do a GET to establish a CSRF token # TestClient isn't used here as we're testing middleware, essentially. req = HttpRequest() CsrfViewMiddleware().process_view(req, login_view, (), {}) # get_token() triggers CSRF token inclusion in the response get_token(req) resp = login_view(req) resp2 = CsrfViewMiddleware().process_response(req, resp) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None) token1 = csrf_cookie.coded_value # Prepare the POST request req = HttpRequest() req.COOKIES[settings.CSRF_COOKIE_NAME] = token1 req.method = "POST" req.POST = {'username': '******', 'password': password, 'csrfmiddlewaretoken': token1} # Use POST request to log in SessionMiddleware().process_request(req) CsrfViewMiddleware().process_view(req, login_view, (), {}) req.META["SERVER_NAME"] = "testserver" # Required to have redirect work in login view req.META["SERVER_PORT"] = 80 resp = login_view(req) resp2 = CsrfViewMiddleware().process_response(req, resp) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, None) token2 = csrf_cookie.coded_value # Check the CSRF token switched self.assertNotEqual(token1, token2)
def auth_view(request): if request.method == 'GET': data = { "username": request.user and request.user.username or None, "csrf_token": get_token(request) } return HttpResponse(json.dumps(data), content_type="application/json") elif request.method == 'POST': from django.contrib.auth import authenticate, login username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) data = { "username": request.user and request.user.username or None, "csrf_token": get_token(request) } json_data = json.dumps(data) return HttpResponse(json.dumps(data), content_type="application/json", status=httplib.OK) else: return HttpResponse("inactive login", content_type="text/plain", status=httplib.FORBIDDEN) else: return HttpResponse("invalid login", content_type="text/plain", status=httplib.FORBIDDEN) elif request.method == 'DELETE': logout(request) return HttpResponse(None, content_type="application/json", status=httplib.OK)
def page(request): from django.middleware.csrf import get_token get_token(request) # force csrf cvars = client_vars(request, drop_last(reverse(page))) dirname = os.path.dirname(os.path.realpath(__file__)) t = Template(open(os.path.join(dirname, 'index.html')).read()); c = RequestContext(request, cvars) return HttpResponse(t.render(c))
def get(self, request, *args, **kwargs): if request.user.is_staff == False: return django.shortcuts.redirect(reverse("frontent.index")) get_token(request) c = {} # See if we can find a set of preferences c.update({"is_logged":request.user.is_authenticated()}) return django.shortcuts.render_to_response("cms/home.html",c,context_instance=django.template.RequestContext(request))
def ClassUserHandle(request): #登录用户才能操作 #判断用户是否登录,登录用户才具备查询权限,并返回当前登录用户 result,lUser = LoginStatus(ltoken=get_token(request)) if not result: #print 'not login',get_token(request),loginUser infor = lUser return JsonResponse(GlobalVar.RspOffLine,infor) #【1】如果方法是Post,则开启注册,这是和客户端交互的第二步 if request.method == 'POST': pClassUserList = JsonRequest(request.body) ClassUserList = [] token = get_token(request) #循环生成ClassUser所有记录之后,再一次性保存到数据库 for pClassUser in pClassUserList[1:]: pidClass = pClassUser['idClass'] pidUser = pClassUser['idUser'] curClassUser = ClassUser( idClass = Class.objects.get(id=pidClass), idUser = User.objects.get(id=pidUser) ) curClassUser.save() #ClassUserList.append(curClassUser) #ClassUser.objects.bulk_create(ClassUserList,token) return JsonResponse(GlobalVar.RspSuccess,u'添加班级成员成功') elif request.method == 'GET': try: #获取学校名字查询关键字 idClass = request.GET.get('idClass','') if idClass == '': return JsonResponse(GlobalVar.RspFail,u"需要提供班级信息") pClass = Class.objects.get(id=idClass) lUsers = User.objects.filter(fkClassUser2User__idClass = idClass).distinct().values(*GlobalVar.TableFields.Userfields) for user in lUsers: #用户在群里面,返回所有用户信息 if user['id'] == lUser.id: lUsers = GetCommonDlList(lUsers) #返回查询结果 return JsonResponse(lUsers) #用户不在群里面,只返回管理员信息 pManager = User.objects.filter(id=pClass.Owner.id).values(*GlobalVar.TableFields.Userfields) pManager = GetCommonDlList(pManager) #返回查询结果 return JsonResponse(pManager) except Class.DoesNotExist: return JsonResponse(GlobalVar.RspFail,"班级不存在") #except User.DoesNotExist: except Exception,ex: return JsonResponse(GlobalVar.RspFail,str(ex))
def admin_pinger(zadanie): if not zadanie.session.get('czy_zalogowany'): return redirect('/admin/logowanie') if zadanie.method != 'POST': # strona pokazująca postęp # obsługa CSRF if zadanie.GET.get('token') != get_token(zadanie): return odpowiedz_nieprawidlowy_token() lista = BramkaProxy.objects if not zadanie.GET.get('wszystkie'): lista = lista.filter(ost_spr_ping__lt=(timezone.now() - datetime.timedelta(days=7))) lista = lista.values_list('ip', flat=True).distinct() # kontekst, szablon kontekst = { 'tytul': 'Pinger \u2022 Panel administracyjny', 'token': get_token(zadanie), 'adres_post': '/admin/pinger', 'lista': lista, } return render(zadanie, 'prx_aplikacja/admin_operacje_ajax.html', kontekst) else: # żądanie AJAX dotyczące pojedynczego IP # aktualnie wybrany IP z listy w JS ip = zadanie.POST.get('wybrany_element', '') # ustalenie portu jakiejkolwiek bramki z tego IP bramki_z_ip = BramkaProxy.objects.filter(ip=ip) if not bramki_z_ip.exists(): raise Http404('Nie znaleziono bramek proxy na podanym IP.') port = port_z_adresu(bramki_z_ip[0].adres) # czas odpowiedzi na żądanie TCP wartosc_ping = ping(ip, port) # aktualizacja dla wszystkich bramek z tego IP BramkaProxy.objects.filter(ip=ip).update( ping=wartosc_ping, ost_spr_ping=timezone.now() ) # przygotowanie odpowiedzi do pokazania na stronie if wartosc_ping is not None: ping_str = floatformat(wartosc_ping, 2) else: ping_str = 'None' return odpowiedz_tekstowa( 'Ping dla ' + ip + ':' + str(port) + ' wynosi ' + ping_str + ' ms.' )
def google_oauth2_csrf(request, value): # type: (HttpRequest, str) -> HttpResponse # In Django 1.10, get_token returns a salted token which changes # everytime get_token is called. try: from django.middleware.csrf import _unsalt_cipher_token token = _unsalt_cipher_token(get_token(request)) except ImportError: token = get_token(request) return hmac.new(token.encode('utf-8'), value.encode("utf-8"), hashlib.sha256).hexdigest()
def home(request): # force the CSRF middleware's process_response to set the token cookie get_token(request) return direct_to_template( request, template="home.html", extra_context={ "user_trusted": request.user.has_perm("map.mappings_trusted") } )
def landing(request): if request.user.is_authenticated(): c = RequestContext(request, { 'csrf': get_token(request), }) return render_to_response('landing.html', c) else: c = RequestContext(request, { 'csrf': get_token(request), }) return render_to_response('landing.html', c)
def post(self, request): serializer = AuthRequestSerializer(data=request.DATA) if serializer.is_valid(): user = serializer.object['user'] if not user.is_active: return Response('Account is not active', HTTP_423_LOCKED) auth.login(request, user) user_serializer = AuthUserSerializer(instance=user) csrf.get_token(request) return Response(user_serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def expose(request): get_token(request) #hFwr0EKBGomGwOesoWhQ9FpiMAvKNA5g #csrftoken=hFwr0EKBGomGwOesoWhQ9FpiMAvKNA5g #output = '' #for key, value in dict(request.META).items(): # output += str(key) + ' ========> ' + str(value) + '<br/>' data = {} for key, value in dict(request.META).items(): data[str(key)] = str(value) return JsonResponse(data)
def render_json(self, request, context, template_name): context = simplify_value(context) resolved = resolve(request.path) context['view_name'] = '%s:%s' % ( self.conf.application_name.split('.')[-1], resolved.url_name) # Include CSRF token, as templates don't get rendered csrf_token is # never called which breaks CSRF for apps written against the JSON API get_token(request) return HttpResponse(simplejson.dumps(context), mimetype="application/json")
def dajaxice_js_import(context): # We must force this request to add the csrftoken cookie. request = context.get('request', None) if request: get_token(request) else: log.warning("The 'request' object must be accesible within the context. \ You must add 'django.contrib.messages.context_processors.request' \ to your TEMPLATE_CONTEXT_PROCESSORS and render your views\ using a RequestContext.") return {'core_url': staticfiles_storage.url('dajaxice/dajaxice.core.js')}
def home(request, file_name=None): get_token(request) static_index_paths = getattr(settings, 'INDEX_PATHS', []) if file_name and file_name in static_index_paths: try: f = open("%s/client/%s" % (settings.ROOT_PATH, file_name), "r") return HttpResponse(f.read()) except: raise Http404 index_file = getattr(settings, 'DEFAULT_INDEX_FILE', 'tank.html') f = open("%s/client/%s" % (settings.ROOT_PATH, index_file), "r") return HttpResponse(f.read())
def process_request (self, request): if request.method == 'GET': get_token(request) request.static_url = settings.STATIC_URL http = 'http://' if request.is_secure(): http = 'https://' request.redirect_uris = (http + request.get_host() + reverse('edit'))
def home(request): get_token(request) how_we_work = get_object_or_404(HowWeWork) page = 1 context = { 'page': page, 'how_we_work':how_we_work } return render(request, 'index.html', context)
def enforce_csrf(self, request): """ Same implementation as django-rest-framework's SessionAuthentication. Enforce CSRF validation for session based authentication. """ reason = CSRFCheck().process_view(request, None, (), {}) if reason: # CSRF failed, bail with explicit error message raise exceptions.PermissionDenied('CSRF Failed: %s' % reason) if not request.COOKIES.get(api_settings.CSRF_COOKIE_NAME): # Make sure the CSRF cookie is set for next time get_token(request)
def process_request(self, request): if (cache_installed() and request.method == "GET" and not request.user.is_authenticated()): cache_key = cache_key_prefix(request) + request.get_full_path() response = cache_get(cache_key) if response is None: request._update_cache = True else: csrf_mw_name = "django.middleware.csrf.CsrfViewMiddleware" if csrf_mw_name in settings.MIDDLEWARE_CLASSES: csrf_mw = CsrfViewMiddleware() csrf_mw.process_view(request, lambda x: None, None, None) get_token(request) return HttpResponse(response)
def HomeView(request): if request.method == 'POST': url = str(request.POST.get('url')) width = request.POST.get('width') height = request.POST.get('height') timeout = request.POST.get('timeout') element = request.POST.get('element') o = urlparse(url) screenshotname = str(o.netloc) + "-" + str(time.time()) + ".png" phantomjs = os.path.join(settings.BUILDOUT_DIR, "bin", "phantomjs") capturejs = os.path.join(settings.BUILDOUT_DIR, "capture.js") outputfile = os.path.join( settings.BUILDOUT_DIR, "var", "media", "captures", screenshotname ) subprocess.call([ phantomjs, capturejs, url, outputfile, width, height, timeout, element, ]) screenshot = Screenshot() screenshot.identifier = slugify(url) screenshot.original_url = url screenshot.fullpath = outputfile screenshot.screenshotname = screenshotname screenshot.save() # return serve(request, outputfile, '/') return HttpResponse(simplejson.dumps({'screenshot':screenshotname}), mimetype='application/json') else: get_token(request) return render_to_response( "lizard_screenshotter/home.html", locals(), context_instance=RequestContext(request) )
def index(request): get_token(request) make_list = Make.objects.all() if request.method == "POST": selected_make = request.POST['makes'] selected_model = request.POST['models'] selected_year = 1 car = Car.objects.get(MAKE=selected_make, MODEL=selected_model) return http.HttpResponseRedirect('./' + str(car.id) + '/') return render_to_response('cars/index.html', {'make_list' : make_list}, RequestContext(request))
def wxLogin(request): #【1】如果方法是Post,提交验证码和电话号码 if request.method == 'POST': wxLogin = JsonRequest(request.body) #pCode = wxLogin.get('code','') pToken = get_token(request) pMsg = wxLogin.get('code','') #【1】用户存在,绑定微信相关id到用户上,并更新用户信息 try: #【1.1】根据电话号码,验证码进行验证,同时会判断该用户是不是已经绑定微信用户 #如果已经绑定,暂时不先解绑,直接覆盖绑定 result1,info1,lUser = loginBest(GlobalVar.LoginWeiXinBond,wxLogin,pToken) #身份校验,验证码比对不通过 if not result1: return JsonResponse(GlobalVar.RspFail,info1) debug('wxLogin','Verify Code is OK') #【1.2】拉取微信用户信息 #如果该用户已经绑定到某个用户的电话号码,需要先解绑,根据openid等查找用户是不是已经绑定 resultBond,inforToken,infoUser = get_weixin_user_first(pMsg) if not resultBond: debug('wxLogin','get weixin user info error',inforToken) return JsonResponse(GlobalVar.RspFail,inforToken) #【1.3】 #【1.4】根据微信用户的信息和数据库中的用户信息进行合并绑定 #lUser=User.objects.get(PhoneNumber=pPhoneNumber) rusult2,infor2 = lUser.wxBond(inforToken,infoUser) if rusult2: #绑定成功,需要上线微信用户 result,infor = LoginStatus(luser=lUser,ltoken=get_token(request)) #不判断登录状态,没有登录成功也不需要重复绑定 """ if result: return JsonResponse(GlobalVar.RspSuccess,infor2) else: return JsonResponse(GlobalVar.RspFail,infor) """ return JsonResponse(GlobalVar.RspSuccess,infor2) else: return JsonResponse(GlobalVar.RspFail,infor2) #【2】用户不存在,直接新注册用户 except Exception,ex: debug('views_weixin->wxLogin->error:',ex) return JsonResponse(GlobalVar.RspFail,'绑定过程发生异常')
def dajaxice_js_import(context, core_url=None): # We must force this request to add the csrftoken cookie. request = context.get('request', None) if request: get_token(request) else: log.warning("The 'request' object must be accesible within the context. \ You must add 'django.contrib.messages.context_processors.request' \ to your TEMPLATE_CONTEXT_PROCESSORS and render your views\ using a RequestContext.") if not core_url or DajaxiceRequest.get_debug(): core_url = '/%s/dajaxice.core.js' % DajaxiceRequest.get_media_prefix() else: core_url = '%s%s' % (settings.STATIC_URL or '', core_url,) return {'core_url': core_url}
def __init__(self, request, *view_args, **view_kwargs): self.request = request self.view_args = view_args self.view_kwargs = view_kwargs self.GET = request.GET self.POST = request.POST self.META = request.META self.method = self.request.method.lower() if self.method in ('get', 'head', 'options'): self.DATA = self.GET elif self.method in ('post', 'put', 'patch', 'delete'): self.DATA = self.POST get_token(self.request)
def process_view(self, request, view_func, view_args, view_kwargs): """ Django session auth Authenticates logged in users. Handy for quick debugging or extensions. Note: Only allows CSRF safe methods. See Django's CSRF AJAX documentation for including tokens to requests: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax """ if request.user.is_authenticated(): # Always set CSRF token (not set by default unless templatetag or ensure_csrf_cookie decorator is used) get_token(request) return None
def send_csrf(request): # just by doing this it will send csrf token back as Set-Cookie header csrf_token = get_token(request) return JsonResponse({'status': 'success', 'data': csrf_token})
def __call__(self, request): if 'x-csrftoken' not in request.headers and request.method=='GET': get_token(request) response = self.get_response(request) return response
def home(request): token = get_token(request) return render(request, 'base_page.html', context={"csrf_token": token})
def csrf_token(self): token = get_token(self.request) return token
def delete_p(request): posts = Post.objects.all().order_by('id') return render_to_response('delete_post.html', {'posts': posts, 'cs': get_token(request)})
def put_post(request): posts=Post.objects.all().order_by('id') return render_to_response('post_update.html', {'posts':posts,'cs':get_token(request)})
def agregarLaguna_asJson(request): if request.method == 'GET': html = '' html += ''' <h1>Registrar Laguna</h1> <form id="formNuevo" action="/compania/agregarLaguna/" class="row" method="POST" > <input type="hidden" name="csrfmiddlewaretoken" value="{}"> <div class="col-md-6 input-group mb-3 mt-2"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Código de Laguna:</span> </div> <label class="text-center"></label> <input type="text" name="codLaguna" maxlength="10" class="form-control" required="" id="id_codLaguna"> </div> <div class="col-md-6"> <label class="text-center">Finca:</label> <select name="finca" class="selectpicker form-control show-tick" required="" id="id_finca" > '''.format(csrf.get_token(request)) finca = Finca.objects.get(pk=request.GET['finca']) html += '<option value="{}" selected>{}</option>'.format( finca.pk, finca) html += ''' </select> </div> <div class="col-md-8"> <label class="text-center">Ubicación:</label> <input type="text" name="ubicacion" maxlength="200" class="form-control" id="id_ubicacion"> </div> <div class="col-md-4"> <label class="text-center">Tamaño:</label> <input type="number" name="tamano" class="form-control" id="id_tamano"> </div> <div class="col-md-12"> <label class="text-center">Descripción:</label> <input type="text" name="descripcion" maxlength="100" class="form-control" id="id_descripcion"> </div> </form> ''' return JsonResponse({'html': html}) elif request.method == 'POST': laguna_form = LagunaForm(request.POST) if laguna_form.is_valid(): laguna = laguna_form.save() lagunas = Laguna.objects.filter(finca=laguna.finca) html = '' for c in lagunas: activo = '' if c.pk == laguna.pk: activo = 'selected' html += '<option value="{}" {}>{}</option>'.format( c.pk, activo, c) return JsonResponse({'html': html}) else: response = JsonResponse( {'error': "información brindada incompleta."}) response.status_code = 403 return response else: return render(request, '404.html')
def dispatch(self, request, *args, **kwargs): return HttpResponse(get_token(request))
def home(req): csrf_token = csrf.get_token(req) context_dict = {'STATIC_URL': settings.STATIC_URL, 'token': csrf_token} return render(req, 'vegapp/main.html', context_dict)
def middleware(request): if not request.COOKIES.get(settings.CSRF_COOKIE_NAME): csrf.get_token(request) response = get_response(request) return response
def get(self, request): csrf_token = csrf.get_token(request) data = {'csrf_token': csrf_token} return Response(data)
def delete(request): users = Users.objects.all().order_by('id') return render_to_response('delete_user.html', {'users': users, 'cs': get_token(request)})
def put(request): users=Users.objects.all() return render_to_response('update user.html', {'users':users,'cs':get_token(request)})
def process_view(self, request, callback, callback_args, callback_kwargs): retval = super(_EnsureCsrfCookie, self).process_view(request, callback, callback_args, callback_kwargs) # Forces process_response to send the cookie get_token(request) return retval
def specific_story(request,pk): cursor = connection.cursor() cursor.execute('SELECT s.id,s.title,s.body,s.date,s.user_id,u.profile_pic,a.first_name FROM story_story s INNER JOIN user_userprofile u ON u.user_id= s.user_id INNER JOIN auth_user a ON u.user_id = a.id AND s.id ='+str(pk)) story = cursor.fetchall() if len(story) > 0 : data = { 'id' : story[0][0], 'title' :story[0][1], 'body' :story[0][2], 'date' :datetime.datetime.fromtimestamp(int(story[0][3])).strftime('%B-%d-%Y'), 'user_id':story[0][4], 'pic' :story[0][5], 'name' :story[0][6] } #adding like dislike cursor.execute("SELECT COUNT(*), types FROM comments_like WHERE story_id = "+str(pk)+" GROUP BY types") result = cursor.fetchall() likeData = {'like':0,'dislike':0} if len(result) >0 : for r in result : likeData[r[1]] = r[0] data['likes'] = likeData #adding comments cursor.execute("SELECT c.id,c.body,c.date,u.first_name,p.profile_pic FROM comments_comment c INNER JOIN auth_user u ON u.id = c.user_id INNER JOIN user_userprofile p ON p.user_id = c.user_id WHERE story_id = "+str(pk) + ' ORDER BY c.date DESC ') comments = cursor.fetchall() commentData = [] if len(comments) >0 : for c in comments : commentData.append({ 'id' :c[0], 'body' : c[1], 'date' : datetime.datetime.fromtimestamp(int(c[2])).strftime('%B-%d-%Y %H:%M:%S'), 'name' : c[3], 'pic' : c[4], 'edit' : data['user_id'] == request.user.id and 'edit' or 'noedit' }) data['comments'] = commentData return render(request,'story/specific_story.html',{'baseurl':request.get_host(),'data':data,'csrf':get_token(request) }) else : return HttpResponse(status=403)
def _get_val(): token = get_token(request) if token is None: return 'NOTPROVIDED' else: return smart_text(token)
def agregarFinca_asJson(request): if request.method == 'GET': html = '' html += ''' <h1>Registrar Finca</h1> <form id='formNuevo' action="/compania/agregarFinca/" class=" form-row" method="POST"> <input type="hidden" name="csrfmiddlewaretoken" value="{}"> <div class="col-md-12 input-group mb-3 mt-2"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Código de Finca</span> </div> <input type="text" name="codFinca" maxlength="10" class="form-control" required="" id="id_codFinca"> </div> <div class="col-md-12 input-group mb-3 mt-2"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Nombre</span> </div> <input type="text" name="nombre" maxlength="50" class="form-control" required="" id="id_nombre"> </div> <div class="col-md-12 input-group mb-3 mt-2"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Abreviatura</span> </div> <input type="text" name="abreviatura" maxlength="10" class="form-control" id="id_abreviatura"> </div> <div class="col-md-12 input-group mb-3 mt-2"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Dirección</span> </div> <input type="text" name="direccion" maxlength="200" class="form-control" required="" id="id_direccion"> </div> <div class="col-md-12 input-group mb-3 mt-2"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Empresa</span> </div> <select name="compania" class="selectpicker form-control" data-live-search="true" required="" id="id_compania" > '''.format(csrf.get_token(request)) companias = Compania.objects.filter(estado=True, tipoCompania=1) for c in companias: html += ''' <option value="{}">{}</option>'''.format(c.pk, c) html += '''</select> </div> </form> ''' return JsonResponse({'html': html}) elif request.method == 'POST': finca_form = FincaForm(request.POST) if finca_form.is_valid(): finca = finca_form.save() fincas = '' if request.POST['todo'] == 'si': fincas = Finca.objects.all() else: fincas = Finca.objects.filter(compania=finca.compania) html = '' print("finca num: ", finca.pk) for c in fincas: activo = '' if c.pk == finca.pk: activo = 'selected' html += '<option value="{}" {}>{}</option>'.format( c.pk, activo, c) return JsonResponse({'html': html}) else: response = JsonResponse( {'error': "información brindada incompleta."}) response.status_code = 403 return response else: return render(request, '404.html')
def post_(request): users=Users.objects.all() return render_to_response('form_post.html', {'users':users,'cs':get_token(request)})
def agregarEmpresa_asJson(request): if request.method == 'GET': html = '' html += ''' <h1>Registrar Empresa</h1> <form id="formNuevo" class="row" method="POST" action="/compania/agregarEmpresa/"> <input type="hidden" name="csrfmiddlewaretoken" value="{}"> <input type="hidden" name="uso" id='uso' value="{}"> <div class="col-md-12 input-group mb-3 mt-2"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Nombre:</span> </div> <input type="text" name="nombre" maxlength="50" class="form-control" required="" id="id_nombre"> </div> <div class="col-md-12 input-group mb-3 mt-2"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Dirección:</span> </div> <input type="text" name="direccion" maxlength="200" class="form-control" required="" id="id_direccion"> </div> <div class="col-md-12 input-group mb-3 mt-2"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Abreviatura:</span> </div> <input type="text" name="abreviatura" maxlength="10" class="form-control" id="id_abreviatura"> </div> <div class="col-md-12 input-group mb-3 mt-2"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Tipo:</span> </div> <label class="text-center"></label> <select name="tipoCompania" class="form-control" required="" id="id_tipoCompania"> '''.format(csrf.get_token(request), request.GET['uso']) tipoEmpresa = TipoCompania.objects.all() for te in tipoEmpresa: html += ''' <option value="{}">{}</option> '''.format(te.pk, te) html += ''' </select> </div> <input hidden type="checkbox" name="estado" class="form-control" id="id_estado" checked> </form> ''' return JsonResponse({'html': html}) elif request.method == 'POST': form = CompaniaForm(request.POST) user = request.user if form.is_valid(): if user.has_perm('compania.add_compania'): compania = form.save() html = '' companias = '' if int(request.POST['uso']) == 1: companias = Compania.objects.filter( tipoCompania=TipoCompania.objects.get(pk=1)) elif int(request.POST['uso']) == 2: companias = Compania.objects.filter( tipoCompania=TipoCompania.objects.get(pk=2)) for var in companias: activo = '' if var.pk == compania.pk: activo = 'selected' html += ''' <option value="{}" {}>{}</option> '''.format(var.pk, activo, var) # elif user.has_perm('compania.change_compania'): # form = CompaniaForm(data = request.POST, instance = Compania.objects.get(pk = int(request.POST['id_o']))) # compania = form.save(commit = False) # compania.save() return JsonResponse({'html': html}) else: response = JsonResponse( {'error': "información brindada incompleta."}) response.status_code = 403 return response else: return render(request, '404.html')
def get_csrf_token(request): token = get_token(request) return HttpResponse(token)